//sku高级生成
(function($, W, D) {
	var oldSkuValue = {};
	$(D).on('click', '#show_Sku', function() {
		$('#skuDrag').empty();
		$('.setVarietas').empty();
		var skuOrder = [];
		var element = document.getElementById("colorsImgTabHead14");
		var element2 = document.getElementById("colorsImgTabHead5");
		// 折叠菜单
		var zhankai = '展开', shouqile = '收起';
		$(D).off('click', '.setVarietas a.setVarietas-a');
		$(D).on('click', '.setVarietas a.setVarietas-a', function() {
			var dataVal = $(this).attr('data-value');
			var aObj = $('.setVarietas a.setVarietas-a'); // 点击当前的(//a标签的自定义属性
															// 0 - 1 切换展开—收起)a标签
			var divId = $(this).data('name'); // unwind_box0 unwind_box1
			var divObj = $('.setVarietas div.setVarietas-word');// 装 颜色 和尺寸的盒子
			divObj.hide();
			aObj.attr('data-value', 0).html(zhankai);
			if (!+dataVal) {
				$(this).attr('data-value', 1).html(shouqile);
				$('#' + divId).show();
			}
		});
		// SKU生成预览（可拖动排序）+ 设置变种代码盒子Box start
		var td = $('#skuVariantList>table>tbody>tr:first td');
		td.each(function(index) {
			var thisId = $(this).attr('id');
			if (thisId) {
				if ($(this).is(':visible')) {
					if (thisId != '200007763') { // 防止发货地显示出来；
						skuOrder.push(thisId);
						// if(index>=2) index = 1;
						var oLi = '<li ishide="0"><div class="pcs " style="border: 1px solid #e8e8e8;" number="' + index + '">' + $(this).text() + '</div></li>';
						$('#skuDrag').append(oLi);
						var oDiv = $('<div class="seting" number="' + index + '" skuId="' + thisId + '"><div class="color" style="color: #333333;font-weight: normal;">' + $(this).text() + '<a href="javascript:" class="unwind setVarietas-a" style="width: 800px;" data-name="show_hide' + index + '" data-value="0">展开</a></div><div class="word setVarietas-word listOut" id="show_hide' + index + '" style="overflow-y: scroll; padding:10px 0 0 20px;"></div></div>');
						$('#skuAttribute span[data-names="attrNames"][id="' + thisId + '"]').closest('tr').find('input[type="checkbox"]:checked').each(function(k) {
							var newNameen = escape($(this).attr("nameen"));
							var dataAll = $(this).closest('tr').next().find('.colorsImg').parent().find('td[cid="' + $(this).attr('data-cid') + '"]').next().find('input[data-names="propertyValueDefinitionName"]').val();
							var s = '';
							if ($(this).closest('#skuAttribute').find('.colorsImg').length < 2) {
								index < 1 ? dataAll == '' ? s = escape($(this).attr('nameen')) : s = dataAll : s = escape($(this).attr('nameen'));
							} else {
								dataAll == '' ? s = escape($(this).attr('nameen')) : s = dataAll;
							}
							var parent = $('<div class="gainword" custom="' + s + '" oldName="' + newNameen + '"><div class="worddfd" style="width: 80px;"><span class="wordCend" data-toggle="tooltip" data-placement="top" title="' + $(this).attr('nameen') + '"">' + $(this).attr('nameen') + '</span></div><input type="text" class="colorSku" value="' + unescape(s) + '"></div>');
							if (oldSkuValue[thisId] && oldSkuValue[thisId][newNameen]) {
								parent.find('input[type="text"]').val(unescape(oldSkuValue[thisId][newNameen]));
							}
							oDiv.find('.listOut').append(parent);
						});
						$('.setVarietas').append(oDiv);
					}
					if ($('.seting').length != 0) {
						var setingDom = $('.seting').eq(0);
						setingDom.find('.word ').show();
						// 判断 让第一个生成SKU列表展示出来
						setingDom.find('a.unwind').attr('data-value', '1').text('收起');
					}
				}
			}
		});
		// end
		// 生成选中sku变种 start
		// skuList();
		$('.worddfd span[data-toggle="tooltip"]').tooltip();
		// SKU生成预览
		var contentTex = '';
		$('.seting').each(function() {
			var text = $(this).find('input.colorSku:first').attr('value');
			contentTex ? contentTex += '-' + text : contentTex += text;
		});
		$('.showSkuCent').val(contentTex);
		// 前缀——连接符——后缀
		$(D).off('keyup', '.PrdfixSkuIpt, .connectorIpt, .suffixIpt, .seting input.colorSku:first');
		$(D).on('keyup', '.PrdfixSkuIpt, .connectorIpt, .suffixIpt, .seting input.colorSku:first', function() {
			slSkuValueHandle();
		});
		function slSkuValueHandle() {
			var prdfixVal = $.trim($('.prdfixSkuIpt').val()), connectorVal = $.trim($('.connectorIpt').val()), suffixVal = $.trim($('.suffixIpt').val());
			var sxArr = sx();
			var slSku = '';
			if (prdfixVal)
				slSku += prdfixVal;
			$.each(sxArr, function(i, j) {
				var skuVal = $.trim($('.seting[number="' + j + '"] input.colorSku:first').val());
				slSku ? slSku += connectorVal + skuVal : slSku += skuVal;
			});
			if (suffixVal)
				slSku += connectorVal + suffixVal;
			$('.showSkuCent').val(slSku);
		}
		function sx() {
			var arr = [];
			$('#skuDrag .pcs').each(function() {
				arr.push($(this).attr('number'))
			});
			return arr;
		}
		// 生成 start
		$(D).off('click', '#skdropdown');
		$(D).on('click', '#skdropdown', function() {
			var skuObj = [];
			oldSkuValue = {};
			$('.seting').each(function() {
				var skuId = $(this).attr('skuId');
				oldSkuValue[skuId] = {};
				var arr = [];
				$(this).find('.gainword').each(function() {
					var obj = {};
					var oldName = $(this).attr('oldName'), newName = escape($.trim($(this).find('input[type="text"]').val())), inpS = escape($(this).attr('custom'));
					obj.skuId = skuId;
					obj.oldName = oldName;
					obj.newName = newName;
					obj.inpS = inpS;
					arr.push(obj);
					oldSkuValue[skuId][oldName] = newName;
				});

				skuObj.push(arr);
			});
			recursiveSolution(skuObj, 0, '', skuObj.length);
			$('#SKUdropdown').modal('hide');
		});
		var recursiveSolution = function(arr, idx, node, len) {
			var str = '', i, obj;
			for (i in arr[idx]) {
				obj = arr[idx][i];
				if (node == '') {
					idx + 1 == len ? skuValueBuild(obj.oldName + '$&$' + obj.newName + '$&$' + obj.skuId) : recursiveSolution(arr, idx + 1, (obj.oldName + '$&$' + obj.newName + '$&$' + obj.skuId), len);
				} else {
					if (idx + 1 == len) {
						obj = node + '$%$' + obj.oldName + '$&$' + obj.newName + '$&$' + obj.skuId;
						skuValueBuild(obj);
					} else {
						recursiveSolution(arr, idx + 1, (node + '$%$' + obj.oldName + '$&$' + obj.newName + '$&$' + obj.skuId), len);
					}
				}
			}
		};
		var skuValueBuild = function(obj) {
			var arr = obj.split('$%$');
			var newObj = {};
			$.each(arr, function(i, j) {
				var listArr = j.split('$&$');
				newObj[listArr[2]] = {};
				newObj[listArr[2]].oldName = listArr[0];
				newObj[listArr[2]].newName = listArr[1];
			});
			// console.log(newObj);
			// console.log(sx());
			var trid = '';
			$.each(skuOrder, function(i, j) {
				trid += newObj[j].oldName;
			});
			var skuTd = $('tr[trId="' + trid + '"] td[data-names="sku"] input[type="text"]');
			var newSku = '';
			var prefix = $('.PrdfixSkuIpt').val();// 前缀
			var connector = $('.connectorIpt').val();// 连接符
			var suffix = $('.suffixIpt').val();// 后缀
			if (prefix)
				newSku += prefix;
			$.each(sx(), function(i, j) {
				var skuId = $('.seting[number="' + j + '"]').attr('skuId');
				var newName = unescape(newObj[skuId].newName);
				newSku ? newSku += connector + newName : newSku += newName;
			});
			if (suffix)
				newSku += connector + suffix;
			if (newSku)
				skuTd.val(newSku);
		};
		// 注册拖拽事件
		$('#skuDrag .pcs').off();
		$('#skuDrag').sortable({
			callback : function() {
				slSkuValueHandle();
			}
		});
		// 弹出模态层
		$('#SKUdropdown').modal('show');
	});
})(jQuery, window, document);
var editorInfo = null;
/*
 * 字符检测 add by fuyi 2015.5.6
 */
var strTesting = function(obj, type) {
	var validateA = /[\u4E00-\u9FA5]/g, // 匹配中文
	validateB = /[\u4E00-\u9FA5;,；，]/g, // 匹配中文、逗号或分号
	validateC = /[\W]/g, // 匹配英文和数字
	validateD = /^[\w-]+$/, // 匹配英文和数字中划线
	validateE = /[^\x00-\xff]/ig, // 中文和全角字符
	validateF = /[^\u0021-\u0024\u0026\u0028-\u003B\u003D\u003F-\u007E]/g, validateG = /([^\x00-\xff]|(<.*?>))/g, validateH = /[^\x00-\x7F]/ig, // 判断非ascii
	validateI = /[^\u0020\u0021-\u0024\u0026\u0028-\u003B\u003D\u003F-\u007E]/g;
	switch (type) {
	case 'subjectTxtNum':
		var num = $('#subject').val().length;
		if (num <= 128) {
			otherNum = 128 - num;
			$('td[data-names="subjectNum"]').html('<span class="fColor2">您还可以输入<span class="fBlue" data-names="subjectNum">' + otherNum + '</span>个字符</span>');
			return true;
		} else {
			otherNum = num - 128;
			$('td[data-names="subjectNum"]').html('<span class="fColor2">您已经超出<span class="fRed" data-names="subjectNum">' + otherNum + '</span>个字符</span>');
			return false;
		}
		break;
	case 'subjectTxt':
		var num = $('#subject').val().length, str = $('#subject').val();
		if (num != 0) {
			if (str.match(validateE)) {
				$('td[data-names="subjectNum"]').append('<span class="fRed mLeft20" data-names="error"><span class="glyphicon glyphicon-remove-circle"></span>对不起，您填写的标题中含有中文字符。</span>');
				return false;
			}
			if (str.match(validateH)) {
				$('td[data-names="subjectNum"]').append('<span class="fRed mLeft20" data-names="error"><span class="glyphicon glyphicon-remove-circle"></span>对不起，您填写的标题中含有非ascii码字符。</span>');
				return false;
			}
			$('td[data-names="subjectNum"]').find('span[data-names="error"]').remove();
			return true;
		} else {
			return false;
		}
		break;
	case 'otherAttr':
		var str = '';
		var i = 0;
		$(obj).closest('div[data-names="otherAttr"]').find('input').each(function() {
			var userAttr = $(this).val();
			if (i > 0) {
				str += "|||";
			}
			str += userAttr;
			i++;
		});
		if (str.match(validateG)) {
			if ($(obj).closest('div[data-names="otherAttr"]').find('span[data-names="attrError"]').length == 0) {
				$(obj).closest('div[data-names="otherAttr"]').append('<span data-names="attrError" style="color:red;margin-left:20px;"><span class="glyphicon glyphicon-remove-circle"></span>自定义属性中请不要包含中文和全角字符！</span>');
			}
			return false;
		} else {
			var strArr = str.split("|||");
			if ($.trim(strArr[0]) == "") {
				$(obj).closest('div[data-names="otherAttr"]').find('span[data-names="attrError"]').remove();
				$(obj).closest('div[data-names="otherAttr"]').append('<span data-names="attrError" style="color:red;margin-left:20px;"><span class="glyphicon glyphicon-remove-circle"></span>自定义属性名不能为空！</span>');
				return false;
			}
			if ($.trim(strArr[1]) == "") {
				$(obj).closest('div[data-names="otherAttr"]').find('span[data-names="attrError"]').remove();
				$(obj).closest('div[data-names="otherAttr"]').append('<span data-names="attrError" style="color:red;margin-left:20px;"><span class="glyphicon glyphicon-remove-circle"></span>自定义属性值不能为空！</span>');
				return false;
			}

			if (strArr[0].length > 40) {
				$(obj).closest('div[data-names="otherAttr"]').find('span[data-names="attrError"]').remove();
				$(obj).closest('div[data-names="otherAttr"]').append('<span data-names="attrError" style="color:red;margin-left:20px;"><span class="glyphicon glyphicon-remove-circle"></span>自定义属性名不能超过40个字符！</span>');
				return false;
			} else {
				$(obj).closest('div[data-names="otherAttr"]').find('span[data-names="attrError"]').remove();
			}
			if (strArr[1].length > 70) {
				$(obj).closest('div[data-names="otherAttr"]').find('span[data-names="attrError"]').remove();
				$(obj).closest('div[data-names="otherAttr"]').append('<span data-names="attrError" style="color:red;margin-left:20px;"><span class="glyphicon glyphicon-remove-circle"></span>自定义属性值不能超过70个字符！</span>');
				return false;
			} else {
				$(obj).closest('div[data-names="otherAttr"]').find('span[data-names="attrError"]').remove();
			}
			if (str.match(validateH)) {
				if ($(obj).closest('div[data-names="otherAttr"]').find('span[data-names="attrError"]').length == 0) {
					$(obj).closest('div[data-names="otherAttr"]').append('<span data-names="attrError" style="color:red;margin-left:20px;"><span class="glyphicon glyphicon-remove-circle"></span>自定义属性中请不要包含非ascii码字符！</span>');
				}
				return false;
			}
			if ((strArr[0].toLowerCase()).indexOf('brand') != -1 || (strArr[1].toLowerCase()).indexOf('brand') != -1) {
				$(obj).closest('div[data-names="otherAttr"]').find('span[data-names="attrError"]').remove();
				$(obj).closest('div[data-names="otherAttr"]').append('<span data-names="attrError" style="color:red;margin-left:20px;"><span class="glyphicon glyphicon-remove-circle"></span>自定义属性内容不能包含“brand”字样！</span>');
				return false;
			}
			return true;
			// $(obj).closest('div[data-names="otherAttr"]').find('span[data-names="attrError"]').remove();
		}
		break;
	case 'propertyValueDefinitionName':
		var str = $(obj).val();
		str = str.replace(/[ ]/g, "");
		if (str.match(validateI)) {
			$(obj).next().html('<span class="glyphicon glyphicon-remove-circle"></span>自定义名称必须为20个字符以内的英文、数字、中划线或下划线！');
			return false;
		} else {
			if (str.length > 20) {
				$(obj).next().html('<span class="glyphicon glyphicon-remove-circle"></span>自定义名称必须为20个字符以内的英文、数字、中划线或下划线！');
				return false;
			} else {
				$(obj).next().html('');
				return true;
			}
		}
		return false;
		break;
	case 'skuCode':
		var str = $(obj).val();
		if ($.trim(str) != '') {
			if (str.match(validateF)) {
				$(obj).next().html('<span class="glyphicon glyphicon-remove-circle"></span>商品编码必须为20个字符以内的英文、数字、中划线或下划线！');
			} else {
				if (str.length > 20) {
					$(obj).next().html('<span class="glyphicon glyphicon-remove-circle"></span>商品编码必须为20个字符以内的英文、数字、中划线或下划线！');
				} else {
					$(obj).next().html('');
					return true;
				}
			}
		} else {
			return true;
		}
		return false;
		break;
	case 'oneSkuCode':
		var str = $(obj).val();
		if ($.trim(str) != '') {
			if (str.match(validateF)) {
				$(obj).next().html('<span class="glyphicon glyphicon-remove-circle"></span>商品编码必须为20个字符以内的英文、数字、中划线或下划线！');
			} else {
				if (str.length > 20) {
					$(obj).next().html('<span class="glyphicon glyphicon-remove-circle"></span>商品编码必须为20个字符以内的英文、数字、中划线或下划线！');
				} else {
					$(obj).next().html('');
					return true;
				}
			}
		} else {
			return true;
		}
		return false;
		break;
	case 'detail':
		var detailT = editorReplaceDisabledTag(editorReplaceAllBlank(smtStrHand.transitionHtml(getEditorData('myj-editor'))));
		var splitStr = '|||';
		var str = trimLabel(detailT, splitStr);
		if (str.match(validateE)) {
			if (str.match("≥") || str.match("≤") || str.match("≠")) {
				return true;
			} else {
				$(obj).html('<span class="glyphicon glyphicon-remove-circle"></span>对不起，您填写的产品详细描述中含有非英文字符，我们已对非英字符黄色标记(若您仍未找到，建议您将内容黏贴在记事本里将格式去掉，再添加到详细描述里试下)！');
				return false;
			}
		} else {
			return true;
		}
		break;
	case 'mobileDetail':
		var detailT = editorReplaceDisabledTag(editorReplaceAllBlank(smtStrHand.transitionHtml(getEditorData('myj-editor-wireless'))));
		var splitStr = '|||';
		var str = trimLabel(detailT, splitStr);
		if (str.match(validateE)) {
			$(obj).html('<span class="glyphicon glyphicon-remove-circle"></span>对不起，您填写的产品详细描述中含有非英文字符！');
			return false;
		} else {
			return true;
		}
		break;
	case 'inputTxt':
		var str = $(obj).val();
		if (str.match(validateC)) {
			// $(obj).val('不能有中文字符！');
			$(obj).next().html('<span class="glyphicon glyphicon-remove-circle" ></span>不能有中文字符');
		} else {
			$(obj).next().html('<span></span>');
			return true;
		}
		break;
	case 'otherTxt':
		var str = $(obj).val();
		if (str.match(validateE)) {
			return false;
		} else {
			return true;
		}
		break;
	}

};
var skuCodeTesting = function() {
	var flag = true;
	$('#skuVariantList').find('input[data-names="skuCode"]').each(function() {
		var obj = $(this);
		flag = flag && strTesting(obj, 'skuCode');
	});
	return flag;
};
var propertyValueTesting = function() {
	var flag = true;
	$('.colorsImg').find('input[data-names="propertyValueDefinitionName"]').each(function() {
		var obj = $(this);
		flag = flag && strTesting(obj, 'propertyValueDefinitionName');
	});
	return flag;
};
var otherAttrTesting = function() {
	var flag = true;
	$('#otherAttr').find('div[data-names="otherAttr"]').each(function() {
		var obj = $(this).find('input:nth-child(2)');
		flag = flag && strTesting(obj, 'otherAttr');
	});
	return flag;
};
var otherAttrAgainTesting = function() {
	var flag = true;
	var hash = {};
	$('#otherAttr').find('div[data-names="otherAttr"]').each(function() {
		var obj = $(this).find('input:nth-child(2)');
		var elem = $(obj).val();
		if (elem != "") {
			if (!hash[elem]) {
				hash[elem] = true;
			} else {
				$(obj).closest('div[data-names="otherAttr"]').find('span[data-names="attrError"]').remove();
				$(obj).closest('div[data-names="otherAttr"]').append('<span data-names="attrError" style="color:red;margin-left:20px;"><span class="glyphicon glyphicon-remove-circle"></span>自定义属性名重复！</span>');
				flag = false;
			}
		}
	});
	return flag;
};
var otherAttrNumTesting = function() {
	var num = $('#otherAttr').find('div[data-names="otherAttr"]').length;

	// 设置序号
	var i = 0;
	$('#otherAttr').find('.serial').each(function() {
		$(this).text(++i);
	});

	if (num > 10) {
		if ($('#otherAttr').find('div[data-names="errorNum"]').length == 0) {
			var str = '<div data-names="errorNum" style="color:red">自定义属性最多添加10个</div>';
			$('#otherAttr').find('button').before(str);
		}
		$("#otherAttr button").removeClass("myj-show");
		$("#otherAttr button").addClass("myj-hide");
		return false;
	} else if (num == 10) {
		$('#otherAttr').find('div[data-names="errorNum"]').remove();
		$("#otherAttr button").removeClass("myj-show");
		$("#otherAttr button").addClass("myj-hide");
		return true;
	} else {
		$('#otherAttr').find('div[data-names="errorNum"]').remove();
		$("#otherAttr button").removeClass("myj-hide");
		$("#otherAttr button").addClass("myj-show");
		return true;
	}
};
var detailTesting = function() {
	var flag = true;

	var detailT = editorReplaceDisabledTag(editorReplaceAllBlank(smtStrHand.transitionHtml(getEditorData('myj-editor'))));
	var splitStr = '|||';
	var detailStr = trimLabel(detailT, splitStr);

	return flag;
};
// add end
var htmlLabel = {
	showType : {
		input : 'text',
		check_box : 'checkbox',
		radio : 'radio',
		list_box : 'select'
	},
	requited : {
		color : 'red',
		val : '*'
	},
	keyAttribute : {
		color : '#48920A',
		val : '!'
	}
};
var skuAttrArr = [];
var showListArr = [];
var brandHtyListArr = [];
var brandHtyListNewArr = [];
var brandOtherList = null;
// 非sku属性展示方法
var productAttributeInit = function(names, id, requitedOld, keyAttribute, showType, values, units, inputType, moreAttribute) {
	var type = '', color = '', text = '', requited = '', html = '';
	type = htmlLabel.showType[showType];
	if (requitedOld == true) {
		color = htmlLabel.requited.color;
		text = htmlLabel.requited.val;
		requited = 'y';
	} else if (keyAttribute == true) {
		color = htmlLabel.keyAttribute.color;
		text = htmlLabel.keyAttribute.val;
		requited = 'n';
	}
	html = '<tr><td class="vAlignTop"><span style="color:' + color + '">' + text + '</span>&nbsp;<span data-names="attrNames" data-type="' + type + '" data-requited="' + requited + '" id="' + id + '">' + names + '</span></td><td>';
	html += valueArrHandle(type, values, units, inputType, moreAttribute, requitedOld, id);
	html += '</td></tr>';
	return html;
};
// 非sku属性关联属性展示方法
var productAttributeInitLine = function(names, id, requitedOld, keyAttribute, showType, values, units, inputType, moreAttribute) {
	var type = '', color = '', text = '', requited = '', html = '';
	type = htmlLabel.showType[showType];
	if (requitedOld == true) {
		color = htmlLabel.requited.color;
		text = htmlLabel.requited.val;
		requited = 'y';
	} else if (keyAttribute == true) {
		color = htmlLabel.keyAttribute.color;
		text = htmlLabel.keyAttribute.val;
		requited = 'n';
	}
	html = '<tr data-names="newTr"><td class="vAlignTop"><span style="color:' + color + '">' + text + '</span>&nbsp;<span data-names="attrNames" data-type="' + type + '" data-requited="' + requited + '" id="' + id + '">' + names + '</span></td><td>';
	html += valueArrHandle(type, values, units, inputType, moreAttribute, requitedOld, id);
	html += '</td></tr>';
	return html;
};
// 非sku数组展示
var valueArrHandle = function(type, arr, units, inputType, moreAttribute, requitedOld, id) {
	arr = eval(arr);
	units = eval(units);
	var str = '<div>';
	if (type == 'select') {
		var haveNone = 0;
		str += '<select attrId="' + id + '" class="chosen-select"';
		if (requitedOld) {
			str += 'formId="form" formType="must" datatype="none" nullmsg="必选属性"';
		}
		str += ' moreAttribute="' + moreAttribute + '" cid="attrSelect"><option data-cid="noValue" value=""> ---- 请选择 ---- </option>';
		if (id == 2 && brandHtyListNewArr.length > 0) {
			// console.log(brandHtyListNewArr);
			str += '<optgroup label="常用品牌">';
			$.each(brandHtyListNewArr, function(k) {
				str += '<option data-cid="' + brandHtyListNewArr[k].brandId + '">' + brandHtyListNewArr[k].brandName + '</option>';
			});
			str += '</optgroup><optgroup label="其它品牌">';
		}
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == '201512802')
				haveNone = 1;
			str += '<option data-cid="' + arr[i].id + '">' + arr[i].names.zh + '(' + arr[i].names.en + ')' + '</option>';
		}
		if (id == 2 && brandHtyListNewArr.length > 0)
			str += '</optgroup>';
		str += '</select>';
		// 品牌临时添加快选按钮 new add at 2016.5.17
		if (id == 2 && haveNone == 1) {
			// str += '<label class="mLeft10"><input class="toValNone"
			// type="checkbox" value="201512802"> 无品牌（none）</label>';
		}
		// 品牌临时添加快选按钮end new add at 2016.5.17
		if (id == 2) {
			str += '<p class="fRed" style="margin-top:5px;">2017年1月3日开始， 除”<a href="http://help.dianxiaomi.cn/pre/getContent.htm?id=292" target="_blank">部分类目</a>”外，新发商品必须选择您的商品所对应的品牌。若不选择品牌或者选择”NONE(无品牌)”，则商品将发布不成功。</p>';
		}
	}
	if (type == 'ridio') {
		for (var i = 0; i < arr.length; i++) {
			str += '<label class="mRight10"><input type="ridio" data-cid="' + arr[i].id + '" name="1" value="' + arr[i].names.zh + '(' + arr[i].names.en + ')' + '">' + arr[i].names.zh + '(' + arr[i].names.en + ')' + '</label>';
		}
	}
	if (type == 'checkbox') {
		for (var i = 0; i < arr.length; i++) {
			str += '<label class="mRight10"><input type="checkbox"';
			if (i == 0 && requitedOld) {
				str += 'formId="form" formType="need1" datatype="none" nullmsg="最少选择一项"';
			}
			str += ' name="check' + id + '" data-cid="' + arr[i].id + '" value="' + arr[i].names.zh + '(' + arr[i].names.en + ')' + '">' + arr[i].names.zh + '(' + arr[i].names.en + ')' + '</label>';
		}
	}
	if (type == 'text') {
		str += '<input type="text" value="" ';
		if (requitedOld) {
			if (inputType == 'NUMBER') {
				str += 'formId="form" formType="must" datatype="none" nullmsg="必填属性"';
			} else {
				str += 'datatype="mustSpaceCheck" nullmsg=""';
			}
		} else if (inputType != 'NUMBER') {
			str += 'datatype="spaceCheck" nullmsg="" '
		}
		if (inputType == 'NUMBER') {
			str += ' data-type="' + inputType + '" onkeyup="value=value.replace(/[^0-9.]/g,\'\');"/>';
		} else {
			str += ' maxLength="70" data-type="' + inputType + '" onkeyup="replaceProperty(this);" "/><span class="fRed mLeft20"></span>';
		}

		if (units != '' && units != undefined) {
			str += '<select data-names="units" style="width:100px;margin-left:10px;">';
			for (var i = 0; i < units.length; i++) {
				str += '<option id="' + units[i].rate + '">' + units[i].unitName + '</option>';
			}
			str += '</select>';
		}
	}

	str += '</div>';
	return str;
};
// 用户常用品牌处理
function brandHistoryHandle() {
	brandHtyListNewArr = [];
	var noneId = 201512802, noneValue = '无品牌（none）';
	var brandHistoryList = $('#brandHistoryList').val();
	var arr = [];
	if (brandOtherList) {
		$.each(brandOtherList, function(i) {
			arr.push(Number(brandOtherList[i].id));
		})
	}
	// console.log($.inArray(noneId,arr));
	if ($.inArray(noneId, arr) != -1) {
		brandHtyListNewArr.push({
			brandId : noneId,
			brandName : noneValue
		});
	}
	// console.log(arr);
	if (brandHistoryList) {
		var brandHtyListArr = JSON.parse(brandHistoryList);
		$.each(brandHtyListArr, function(i) {
			var id = Number(brandHtyListArr[i].brandId);
			// console.log(id);
			if ($.inArray(id, arr) != -1 && id != noneId) {
				brandHtyListNewArr.push(brandHtyListArr[i]);
			}
		})
	}
}
// 店铺切换后品牌常用选项处理;
function brandHistoryChange() {
	var selObj = $('#productAttribute select[attrid="2"]');
	var oldSelVal = selObj.val();
	brandHistoryHandle();
	var str = '<option data-cid="#{id}">#{namesZh}(#{namesEn}）</option>';
	var other = '<option data-cid="#{brandId}">#{brandName}</option>';
	var newStr = '<option data-cid="noValue" value=""> ---- 请选择 ---- </option>';
	if (brandHtyListNewArr.length > 0) {
		newStr += '<optgroup label="常用品牌">';
		$.each(brandHtyListNewArr, function(k) {
			str += other.formatOther(brandHtyListNewArr[k]);
		});
		newStr += '</optgroup><optgroup label="其它品牌">';
	}
	if (brandOtherList) {
		$.each(brandOtherList, function(i) {
			brandOtherList[i].namesZh = brandOtherList[i].names.zh;
			brandOtherList[i].namesEn = brandOtherList[i].names.en;
			newStr += str.formatOther(brandOtherList[i]);
		})
	}
	if (brandHtyListNewArr.length > 0) {
		newStr += '</optgroup>';
	}
	selObj.html(newStr).val(oldSelVal);
	selObj.find('option[data-cid="noValue"]').attr('selected', 'selected');
	selObj.closest('div').find(".chosen-select").trigger("chosen:updated");
	selObj.closest('div').find(".chosen-select").chosen({
		search_contains : true
	// 注册插件
	})
}
// 品牌临时添加快选按钮click动作 new add at 2016.5.17
$(document).on('click', 'input.toValNone', function() {
	var valId = $(this).val();
	var checked = $(this).is(':checked');
	var select = $(this).closest('div').find('select');
	var option = select.find('option[data-cid="' + valId + '"]');
	if (checked) {
		if (option.length > 0) {
			select.val(option.val());
			option.prop('selected', 'selected');
			select.trigger("chosen:updated");
		} else {
			$.fn.message({
				type : "warning",
				msg : "此分类品牌没有「无品牌」选项"
			});
		}
	} else {
		select.val('');
	}
	select.trigger("chosen:updated");
});
$(document).on('change', 'select[attrId="2"]', function() {
	var optCid = $(this).find('option:selected').attr('data-cid');
	if (optCid != '201512802') {
		$('input.toValNone').prop('checked', false);
	} else {
		$('input.toValNone').prop('checked', true);
	}
});
// 品牌临时添加快选按钮click动作 new add at 2016.5.17
// sku属性展示方法
var productSkuInit = function(names, namesEn, id, requitedOld, keyAttribute, showType, values, spec, customizedName, customizedPic, inputType) {
	var type = '', color = '', text = '', html = '', requited = '', skuAttr = {};

	skuAttrArr.push({
		id : id,
		name : names,
		nameEn : namesEn,
		spec : spec,
		clickData : []
	});
	// type = htmlLabel.showType[showType];
	type = 'checkbox';
	if (requitedOld == true) {
		color = htmlLabel.requited.color;
		text = htmlLabel.requited.val;
		requited = 'y';
	} else if (keyAttribute == true) {
		color = htmlLabel.keyAttribute.color;
		text = htmlLabel.keyAttribute.val;
		requited = 'n';
	}
	if (names == '发货地') {
		html = '<tr><td><span style="color:' + color + '">' + text + '</span>&nbsp;<span data-names="attrNames" data-requited="' + requited + '" data-type="' + type + '" id="' + id + '" customizedName=' + customizedName + ' customizedPic=' + customizedPic + '>' + names + '：</span></td><td><div style="width:100%;padding-top:3px;">(<span class="fRed">非海外仓用户请勿勾选</span>)<a href="javascript:;" style="margin-left:20px;" data-name="fhd" data-values="close">+ 展开</a></div><div style="width:100%;margin-top:5px;display:none" id="fhd">';
	} else {
		html = '<tr><td><span style="color:' + color + '">' + text + '</span>&nbsp;<span data-names="attrNames" data-requited="' + requited + '" data-type="' + type + '" id="' + id + '" customizedName=' + customizedName + ' customizedPic=' + customizedPic + '>' + names + '：</span></td><td><div>';
	}
	html += skuArrHandle(type, values, namesEn, names, id, spec, customizedName, customizedPic);
	html += '</div></td><tr>';
	return html;

};
// sku数组展示
var skuArrHandle = function(type, arr, namesEn, name, id, spec, customizedName, customizedPic) {
	arr = eval(arr);
	var str = '<div>';
	switch (type) {
	case 'select':
		str += '<select>';
		$.each(arr, function(i, j) {
			str += '<option data-cid="' + j.id + '">' + j.names.zh + '(' + j.names.en + ')' + '</option>';
		});
		str += '</select>';
		break;
	case 'ridio':
		$.each(arr, function(i, j) {
			str += '<label class="mRight10"><input type="ridio" data-cid="' + j.id + '" name="1" value="' + j.names.zh + '(' + j.names.en + ')' + '">' + j.names.zh + '(' + j.names.en + ')' + '</label>';
		});
		break;
	case 'checkbox':
		if (customizedPic == 1 || customizedName == 1) {
			$.each(arr, function(i, j) {
				str += '<label class="mRight10" style="min-width:120px;" title="' + j.names.en + '"><input data-cilck="checkbox" type="checkbox" data-cid="' + j.id + '" nameZh="' + j.names.zh + '" nameEn="' + j.names.en + '" spec="' + spec + '" pid="' + id + '">';
				if (id == 14 || id == 200000049) {
					str += '&nbsp;<span style="border:1px solid #eee;display:inline-block;position:relative;top:2px;width:14px;height:14px;background-color:' + (j.names.en).replace(/ /, "") + '" title="' + j.names.en + '"></span>';
				}
				str += '&nbsp;' + j.names.zh + '</label>';
			});
			if (customizedPic == 1 && customizedName == 1) {
				str += '<tr><td></td><td><div id="colorsImg' + id + '" class="colorsImg"><table class="myj-table"><tr id="colorsImgTabHead' + id + '" class="colorsImgTabHead"><th>' + name + '</th><th>自定义名称</th><th colspan="2">图片（无图可忽略）</th></tr></table></div></td></tr>';
			}
			if (customizedPic == 0 && customizedName == 1) {
				str += '<tr><td></td><td><div id="colorsImg' + id + '" class="colorsImg"><table class="myj-table otherColorImgList"><tr id="colorsImgTabHead' + id + '" class="colorsImgTabHead"><th>' + name + '</th><th>自定义名称</th></tr></table></div></td></tr>';
			}
			if (customizedPic == 1 && customizedName == 0) {
				str += '<tr><td></td><td><div id="colorsImg' + id + '" class="colorsImg"><table class="myj-table"><tr id="colorsImgTabHead' + id + '" class="colorsImgTabHead"><th>' + name + '</th><th>图片（无图可忽略）</th></tr></table></div></td></tr>';
			}
		} else {
			$.each(arr, function(i, j) {
				str += '<label class="mRight10" style="min-width:160px;"><input data-cilck="checkbox" type="checkbox" data-cid="' + j.id + '" nameZh="' + j.names.zh + '" nameEn="' + j.names.en + '"  spec="' + spec + '" pid="' + id + '">' + j.names.zh + '(' + j.names.en + ')' + '</label>';
			});
		}
		break;
	case 'text':
		str += '<input type="text" value="">';
		break;
	}
	str += '</div>';
	return str;
};
// 类目全部属性展示
var showProductAttribute = function(objArr, updateSkuAttr, language) {
	$('#productAttribute').empty();
	skuAttrArr = [];
	showListArr = [];
	var strStar = '<table>', strEnd = '</table>', attrStr = '', skuStr = '';
	for (var i = 0; i < objArr.length; i++) {
		var sku = objArr[i].sku, showType = objArr[i].attributeShowTypeValue, names = objArr[i].nameZh, namesEn = objArr[i].nameEn, required = objArr[i].required, keyAttribute = objArr[i].keyAttribute, namesId = objArr[i].arrtNameId, spec = objArr[i].spec, visible = objArr[i].viseble, values = objArr[i].values, customizedName = objArr[i].customizedName, customizedPic = objArr[i].customizedPic, units = objArr[i].units, inputType = objArr[i].inputType, moreAttribute = objArr[i].moreAttribute;
		if (language == 'en') {
			names = objArr[i].nameEn;
		}
		if (sku == false) {
			// 调用非sku属性展示方法
			if (namesId == 2) {
				if (values) {
					brandOtherList = JSON.parse(values);
				}
				brandHistoryHandle();// 用户常用品牌处理
				// console.log(values);
				brandHistoryChange();
			}
			attrStr += productAttributeInit(names, namesId, required, keyAttribute, showType, values, units, inputType, moreAttribute);
		} else {
			// 调用sku属性展示方法
			skuStr += productSkuInit(names, namesEn, namesId, required, keyAttribute, showType, values, spec, customizedName, customizedPic, inputType);
		}
	}
	$('#productAttribute').html(strStar + attrStr + strEnd);
	if (updateSkuAttr) {
		$('#skuAttribute').empty();
		$('#skuVariantList table').empty();
		$('#skuAttribute').html(strStar + skuStr + strEnd);
	}
	$('.colorsImgTabHead th').hide();
	// 注册可搜索sel方法
	$(".chosen-select").chosen({
		search_contains : true
	// 注册插件
	});
	// sku点击方法
	$(document).off('click', 'input[data-cilck="checkbox"]');
	$(document).on('click', 'input[data-cilck="checkbox"]', function() {
		var id = $(this).attr('data-cid'), pid = $(this).attr('pid'), spec = $(this).attr('spec'), nameZh = $(this).attr('nameZh'), nameEn = $(this).attr('nameEn'), customizedPic = $(this).closest('tr').find('span[data-names="attrNames"]').attr('customizedPic'), customizedName = $(this).closest('tr').find('span[data-names="attrNames"]').attr('customizedName');
		var obj = {
			nameEn : nameEn,
			nameZh : nameZh,
			id : id,
			pid : pid,
			spec : spec,
			customizedPic : customizedPic,
			customizedName : customizedName
		};
		var str = '<tr>';
		for (var i = 0; i < skuAttrArr.length; i++) {
			str += '<td id=' + skuAttrArr[i].id + '>' + skuAttrArr[i].name + '</td>';
		}
		str += '<td><span class="fRed">*</span> 零售价</td><td>实际收入</td><td data-names="bulkDiscount">批发价</td><td><span class="fRed">*</span> 库存</td><td>商品编码（<a href="javascript:;" onclick="showSkuStock();">自动生成<span style="color:black"> • </span><a href="javascript:;" id="show_Sku" name="0">高级</a></a>）</td></tr>';
		skuListTemporaryDataGet();
		$('#skuVariantList table').html('');
		$('#skuVariantList table').append(str);
		var isChecked = $(this).is(':checked');
		$.each(skuAttrArr, function(i, j) {
			if (j.id == pid) {
				if (isChecked) {
					if (customizedPic == 1 || customizedName == 1) {
						colorsImgShow(id, nameZh, nameEn, pid, customizedPic, customizedName);
						$('#colorsImgTabHead' + pid + ' th').show();
					}
					j.clickData.push(obj);
				} else {
					if (customizedPic == 1 || customizedName == 1) {
						colorsImgHide(id, nameZh, nameEn, pid, customizedPic, customizedName);
						var num = $('#colorsImg' + pid + ' table').find('td').length;
						if (num == 0) {
							$('#colorsImgTabHead' + pid + ' th').hide();
						}
					}
					for (var k = 0; k < j.clickData.length; k++) {
						if (j.clickData[k].id == id) {
							j.clickData.splice(k, 1);
						}
					}
				}
				skuShowList();
			}
		});
	});
};

/**
 * 点击选中类目
 */
$(document).on('click', '.selectCategory', function() {
	var categoryId = $(".selectCategoryId .categoryNames").attr("categoryId");
	var oldCategoryId = $("#categoryId").val();

	if (categoryId == oldCategoryId) {
		$('#categoryChoose').modal('hide');
	} else {
		// 判断是否是叶子节点
		var obj = $('#categoryChoose .categoryChooseOutDiv .categoryChooseInDiv span[categoryid="' + categoryId + '"]');
		var isleaf = $(obj).next().attr('data-isleaf');
		if (isleaf == 0) {
			var cateName = $(obj).text();
			$.fn.message({
				type : "error",
				msg : "您选择的类目 “" + cateName + "” 还有子类目,请选择子类目！"
			});
			return;
		}

		$.ajax({
			type : 'POST',
			async : false,
			url : 'smtCategory/attributeList.json',
			data : {
				categoryId : categoryId
			},
			dataType : 'json',
			success : function(data) {
				$('#categoryChoose').modal('hide');
				$("#categoryId").val(categoryId);

				// 显示类目属性
				showProductAttribute(data, true);
				$(".productInfoModule .productInfoModule-content .category").html($(".categoryChooseCrumbs").html());

				// 选中下拉
				getNewCategoryHistory(categoryId);

				// 初始化价格和库存
				priceAndStock();

				// 类目尺码
				downloadSizeChartList();
			}
		});
	}
});

// 获取属性的自属性
function childAttributeList(arrtNameId, arrtValueId) {
	var categoryId = $("#categoryId").val();
	var dataArr = [];
	$.ajax({
		type : 'POST',
		async : false,
		url : 'smtCategory/childAttributeList.json',
		data : {
			categoryId : categoryId,
			arrtNameId : arrtNameId,
			arrtValueId : arrtValueId
		},
		dataType : 'json',
		success : function(data) {
			dataArr = data;
		}
	});
	return dataArr;
}

// 数组中单个元素删除方法,未用到
function arrDel(arr, delVal) {
	for (var i = 0; i < arr.length; i++) {
		if (arr[i] == delVal) {
			arr.splice(i, 1);// splice方法
			return arr;
		}
	}
}
// 颜色添加图片列表
var colorsImgShow = function(id, nameZh, nameEn, pid, customizedPic, customizedName) {
	var str = '';
	if (customizedPic == 1 && customizedName == 1) {
		str = '<tr><td cid="' + id + '" pid="' + pid + '">' + nameZh + '</td><td><input type="text" maxlength="20" data-names="propertyValueDefinitionName" onkeyup="replaceCustomCode(this);" /><div class="propertyError fRed"></div></td><td style="width:120px;text-align:left;border-right:none;" class="imgTd"><div></div>' + '</td><td style="border-left:none;width:100px;"><div class="dropdown">' + '<button class="btn btn-myj-default" type="button" id="dropdownMenuImport3" data-toggle="dropdown" aria-expanded="true">' + '选择图片<span class="caret"></span></button>' + '<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu2">' + '<li role="presentation"><a role="menuitem" tabindex="-1" href="javascript:;" data="' + id + '" onclick="uploadImg(1,' + id + ');">本地图片</a></li>' + '<li role="presentation"><a role="menuitem" tabindex="-1" href="javascript:;" onclick="uploadImg(2,' + id + ');">网络图片</a></li>' + '<li role="presentation"><a role="menuiten" tabindex="-1" href="javascript:;" onclick="uploadImg(3,' + id + ')">空间图片</a></li>' + '<li role="presentation"><a role="menuitem" tabindex="-1" href="javascript:;" onclick="uploadImg(4,' + id + ')">图片银行</a></li>' + '<li role="presentation"><a role="menuitem" tabindex="-1" href="javascript:;" onclick="uploadImg(6,' + id + ');">引用采集图片</a></li>' + '</ul></div>' + '</td></tr>';
	}
	if (customizedPic == 0 && customizedName == 1) {
		str = '<tr><td cid="' + id + '" pid="' + pid + '">' + nameZh + '</td><td><input type="text" maxlength="20" data-names="propertyValueDefinitionName" onkeyup="replaceCustomCode(this);" /><div class="propertyError fRed"></div></td></tr>';
	}
	if (customizedPic == 1 && customizedName == 0) {
		str = '<tr><td cid="' + id + '" pid="' + pid + '">' + nameZh + '</td><td style="width:120px;text-align:left;border-right:none;" class="imgTd"><div></div>' + '</td><td style="border-left:none;width:100px;"><div class="dropdown">' + '<button class="btn btn-myj-default" type="button" id="dropdownMenuImport3" data-toggle="dropdown" aria-expanded="true">' + '选择图片<span class="caret"></span></button>' + '<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu2">' + '<li role="presentation"><a role="menuitem" tabindex="-1" href="javascript:;" data="' + id + '" onclick="uploadImg(1,' + id + ');">本地图片</a></li>' + '<li role="presentation"><a role="menuitem" tabindex="-1" href="javascript:;" onclick="uploadImg(2,' + id + ');">网络图片</a></li>' + '<li role="presentation"><a role="menuiten" tabindex="-1" href="javascript:;" onclick="uploadImg(3,' + id + ')">空间图片</a></li>' + '<li role="presentation"><a role="menuitem" tabindex="-1" href="javascript:;" onclick="uploadImg(4,' + id + ')">图片银行</a></li>' + '<li role="presentation"><a role="menuitem" tabindex="-1" href="javascript:;" onclick="uploadImg(6,' + id + ');">引用采集图片</a></li>' + '</ul></div>' + '</td></tr>';
	}
	$('#colorsImg' + pid + ' table').append(str);
	/*
	 * if($("#uploadImgInputDiv div[data="+id+"].uploadSkuImg").attr("data") ==
	 * undefined){ $("#uploadImgInputDiv").append('<div class="myj-hide
	 * uploadSkuImg" data="'+id+'"/>'); imageUpload($("#uploadImgInputDiv
	 * div[data="+id+"].uploadSkuImg")); }
	 */
};
// 颜色删除图片列表
var colorsImgHide = function(id, nameZh, nameEn, pid) {
	$('#colorsImg' + pid + ' table').find('td[cid="' + id + '"]').closest('tr').remove();
};
// 图片删除
$(document).on('click', '.glyphicon-remove-sign', function() {
	$(this).closest('.imgDivOut').remove();
});
// 变种添加图片
function skuImg(colorObj, url) {
	var load = '<span class="aMakeRemoveBtn glyphicon-remove-sign smtAMakeRemoveBtnLocation"></span>';
	if (url.indexOf("loadingSm.gif") >= 0) {
		load = '';
	}
	var pid = $('.colorsImg').find('td[cid="' + colorObj + '"]').attr('pid');
	// 图片编辑 fuyi 2015.7.16
	var str = '<div class="imgDivOut out"><div class="imgDivIn"><img src="' + url + '" class="imgCss"/>' + load + '</div><a href="javascript:void(0);" data-names="onLineHandleImg">在线美图</a></div>';
	var obj = $('#colorsImg' + pid).find('td[cid="' + colorObj + '"]').closest('tr').find('td.imgTd');
	$(obj).find('div:first-child').html(str);

}
// 临时sku列表数据存储数组
var skuListDataObj = [];
// 临时sku列表数据存储
function skuListTemporaryDataGet() {
	skuListDataObj = [];
	$('#skuVariantList tr[data-name="skuProperty"]').each(function() {
		var obj = {}, id = $(this).attr('trId');
		obj['id'] = id;
		obj['price'] = $(this).find('td[data-names="price"] input[type="text"]').val();
		obj['skuPrice'] = $(this).find('td[data-names="skuPrice"]').html();
		obj['bulkDiscount'] = $(this).find('td[data-names="bulkDiscount"]').html();
		obj['num'] = $(this).find('td[data-names="num"] input[type="text"]').val();
		obj['sku'] = $(this).find('td[data-names="sku"] input[type="text"]').val();
		skuListDataObj.push(obj);
	})
}
// 生成sku列表每条独立的id
var skuListIdBuild = function() {
	$('#skuVariantList tr[data-name="skuProperty"]').each(function(index) {
		var id = '', pushId = 'trID';
		$(this).find('td[data-names="property"]').each(function() {
			if ($(this).attr('pid') != '200007763') {
				id += escape($(this).attr('data-value'));
			}
			pushId += $(this).attr('cid');
		});
		$(this).attr('trId', id).attr('pushId', pushId);
		$(this).closest('.productInfoModule-content').find('#colorsImg14').find('input[data-names="propertyValueDefinitionName"]').eq(index).attr('nameen', id);
	})
};
// sku列表数据回填
function skuListTemporaryDataPush() {
	// console.log(skuListDataObj);
	$(skuListDataObj).each(function(i, j) {
		var trObj = $('#skuVariantList').find('tr[trId="' + j.id + '"]');
		trObj.find('td[data-names="price"] input[type="text"]').val(j.price);
		trObj.find('td[data-names="skuPrice"]').html(j.skuPrice);
		trObj.find('td[data-names="bulkDiscount"]').html(j.bulkDiscount);
		trObj.find('td[data-names="num"] input[type="text"]').val(j.num);
		trObj.find('td[data-names="sku"] input[type="text"]').val(j.sku);
	})
}
// sku变种生成
var skuShowList = function() {
	showListArr = [];
	// 把不是空的sku数组拿出来交给testAll方法
	$.each(skuAttrArr, function(i, j) {
		var arr = j.clickData;
		if (arr.length != 0) {
			showListArr.push(arr);
		}
	});
	var len = showListArr.length;
	priceAndStock(showListArr);
	// $('#skuVariantList table').html('');
	testAll(showListArr, 0, '', len);
	skuListIdBuild();
	skuListTemporaryDataPush();
};
function priceAndStock(arr) {
	var len = 0;
	if (arr == null || arr == undefined) {
		len = 0;
	} else {
		len = arr.length;
	}
	if (len == 0) {
		$('#skuVariantList table tr:nth-child(1) td').hide();
		$('#priceAndStockA .tdA, #priceAndStockA .tdB').show();
		$('#priceAndStockB').closest('tr').hide();
		var clone2 = $('.setUpNationalFre').clone(true);
		$('.setUpNationalFre').remove();
		$('#retail').after(clone2);
	} else {
		$('#skuVariantList table tr:nth-child(1) td').show();
		$('#priceAndStockB').closest('tr').show();
		$('#priceAndStockA .tdA, #priceAndStockA .tdB').hide();
		var clone1 = $('.setUpNationalFre').clone(true);
		$('.setUpNationalFre').remove();
		$('#deliveryTime').closest('tr').before(clone1);
	}
}
function testAll(arr, idx, node, len) {
	var str = '';
	if (idx + 1 == len) {
		for ( var i in arr[idx]) {
			var obj = arr[idx][i];
			if (node == '') {
				str = skuListHtml(obj.id + '$&' + obj.nameZh + '$&' + obj.pid + '$&' + obj.nameEn + '$&' + obj.customizedName + '$&' + obj.customizedPic);

			} else {
				obj = node + ',' + obj.id + '$&' + obj.nameZh + '$&' + obj.pid + '$&' + obj.nameEn + '$&' + obj.customizedName + '$&' + obj.customizedPic;
				str = skuListHtml(obj);
			}
		}
	} else {
		for ( var i in arr[idx]) {
			var obj = arr[idx][i];
			if (node == '') {
				testAll(arr, idx + 1, (obj.id + '$&' + obj.nameZh + '$&' + obj.pid + '$&' + obj.nameEn + '$&' + obj.customizedName + '$&' + obj.customizedPic), len);
			} else {
				testAll(arr, idx + 1, (node + ',' + obj.id + '$&' + obj.nameZh + '$&' + obj.pid + '$&' + obj.nameEn + '$&' + obj.customizedName + '$&' + obj.customizedPic), len);
			}
		}
	}
}
var skuListHtml = function(str) {
	var newArr = [];
	newArr = str.split(',');
	var str = '<tr data-name="skuProperty">';
	for (var i = 0; i < skuAttrArr.length; i++) {
		var id = skuAttrArr[i].id;
		$('#skuVariantList table').find('td[id="' + id + '"]').hide();
	}
	for (var i = 0; i < newArr.length; i++) {

		var arr = newArr[i].split('$&');
		$('#skuVariantList table').find('td[id="' + arr[2] + '"]').show();
		str += '<td cid=' + arr[0] + ' pid=' + arr[2] + ' data-value="' + arr[3] + '" data-names="property" customizedName="' + arr[4] + '" customizedPic="' + arr[5] + '">' + arr[1] + '</td>';
	}
	str += '<td data-names="price"><input type="text" class="smInput" formType="skuPrice" datatype="skuPrice" nullmsg="请填写零售价"  onkeyup="clearNoNum(this)" data-names="skuPrice"/></td><td data-names="skuPrice"><span data-names="skuPrice">$0.00</span></td><td data-names="bulkDiscount"><span data-names="bulkDiscount">--</span></td><td data-names="num"><input type="text" class="smInput" data-names="ipmSkuStock" formType="must" datatype="must" nullmsg="请填写库存" onkeyup="clearMistakeNumber(this)"/></td><td data-names="sku"><input type="text" data-names="skuCode" maxlength="20" onkeyup="replaceSkuCode(this);"/><div class="fRed skuCodeError"></div></td></tr>';
	$('#skuVariantList table').append(str);
};

var replaceSkuCode = function(e) {
	var t = /[^\u0021-\u0024\u0026\u0028-\u003B\u003D\u003F-\u007E]/g;
	var n = e.keyCode;
	if (n === 8)
		return;
	var val = $(e).val();
	if (t.test(val)) {
		$(e).val($(e).val().replace(t, ""));
	}
};
var replaceCustomCode = function(e) {
	var t = /[^\u0020\u0021-\u0024\u0026\u0028-\u003B\u003D\u003F-\u007E]/g;
	var n = e.keyCode;
	if (n === 8)
		return;
	var val = $(e).val();
	if (t.test(val)) {
		$(e).val($(e).val().replace(t, ""));
	}
};

var replaceProperty = function(e) {
	var t = /([^\x00-\xff]|(<.*?>))/g;
	var val = $(e).val();
	if (t.test(val)) {
		$(e).val($(e).val().replace(t, ""));
	}
};

// 非SKU属性获取方法
var attrDataGet = function(objA, objB, isCheck) {
	if (objA == '' || objA == undefined) {
		objA = 'productAttribute';
	}
	if (objB == '' || objB == undefined) {
		objB = 'otherAttr';
	}
	var arr = [], objA = '#' + objA, objB = '#' + objB, errorArr = [], otherErrorArr = [];
	$(objA).find('tr').each(function() {
		var nameObj = $(this).find('td:first-child').find('span[data-names="attrNames"]'), attrObj = $(this).find('td:last-child'), attrNameId = $(nameObj).attr('id'), requited = $(nameObj).attr('data-requited'), attrValue = '', attrValueId = '', type = $(nameObj).attr('data-type');
		if (type == 'text') {
			attrValue = ($(attrObj).find('input[type="text"]').val());
			attrValue = $.trim(attrValue);
			if (requited == 'y') {
				if (attrValue == '' || attrValue == undefined) {
					var names = $(nameObj).html();
					errorArr.push(names);
				}
			}
			if (attrValue != '' && attrValue != undefined) {
				if ($(attrObj).find('select[data-names="units"]').length > 0) {
					attrValue = ($(attrObj).find('input[type="text"]').val()).replace(/[ ]/g, '') + ' ' + $(attrObj).find('select[data-names="units"]').val();
				}
				attrValue = $.trim(attrValue);
				attrNameId = parseInt(attrNameId);
				arr.push({
					attrNameId : attrNameId,
					attrValue : attrValue
				});
			}
		}
		if (type == 'checkbox') {
			if (requited == 'y') {
				if ($(attrObj).find('input[type="checkbox"]:checked').length == 0) {
					var names = $(nameObj).html();
					errorArr.push(names);
				}
			}
			$(attrObj).find('input[type="checkbox"]').each(function() {
				if (this.checked) {
					attrValueId = $(this).attr('data-cid');
					attrValueId = parseInt(attrValueId);
					attrNameId = parseInt(attrNameId);
					var otherVal = '';
					if (attrValueId == 4) {
						otherVal = $.trim($(this).closest('label').next().val());
						arr.push({
							attrNameId : attrNameId,
							attrValueId : attrValueId,
							attrValue : otherVal
						});
					} else {
						arr.push({
							attrValueId : attrValueId,
							attrNameId : attrNameId
						});
					}
				}
			});
		}
		if (type == 'select') {
			attrValueId = $(attrObj).find('select option:selected').attr('data-cid');
			if (requited == 'y') {
				if (attrValueId == 'noValue') {
					var names = $(nameObj).html();
					errorArr.push(names);
				}
			}
			if (attrValueId != 'noValue') {
				attrValueId = parseInt(attrValueId);
				attrNameId = parseInt(attrNameId);
				var otherVal = '';
				if (attrValueId == 4) {
					otherVal = $.trim($(attrObj).find('input[data-names="otherIpt"]').val());
					if (otherVal == '') {
						var names = $(nameObj).html();
						otherErrorArr.push(names);
					}
					arr.push({
						attrNameId : attrNameId,
						attrValueId : attrValueId,
						attrValue : otherVal
					});
				} else {
					arr.push({
						attrValueId : attrValueId,
						attrNameId : attrNameId
					});
				}
			}
		}
		if (type == 'radio') {
			$(attrObj).find('input[type="radio"]').each(function() {
				if (this.checked) {
					attrValueId = $(this).attr('data-cid');
					attrValueId = parseInt(attrValueId);
					attrNameId = parseInt(attrNameId);
					arr.push({
						attrValueId : attrValueId,
						attrNameId : attrNameId
					});
				}
			});
		}

	});
	$(objB).find('div').each(function() {
		var attrName = $.trim($(this).find('input:nth-child(2)').val()), attrValue = $.trim($(this).find('input:nth-child(3)').val());
		if (attrName != '' && attrName != undefined && attrValue != '' && attrValue != undefined)
			arr.push({
				attrValue : attrValue,
				attrName : attrName
			});
	});
	// 提交验证（必填和other）
	if (isCheck) {
		var errorName = '', otherErrorName = '', dayton = '、';
		if (errorArr.length != 0) {
			if (otherErrorArr.length != 0) {
				$.each(otherErrorArr, function(m, j) {
					m > 0 ? otherErrorName += dayton + otherErrorArr[m] : otherErrorName += otherErrorArr[m];
				})
			}
			$.each(errorArr, function(n, j) {
				n > 0 ? errorName += dayton + errorArr[n] : errorName += errorArr[n];
			});
			if (otherErrorName != '') {
				$.fn.message({
					type : "error",
					msg : errorName + "为必填属性！<br/>" + otherErrorName + "属性的other值不能为空！",
					existTime : "20000"
				});
			} else {
				$.fn.message({
					type : "error",
					msg : errorName + "为必填属性！",
					existTime : "20000"
				});
			}
			return null;
		} else if (otherErrorArr.length != 0) {
			$.each(otherErrorArr, function(m, j) {
				m > 0 ? otherErrorName += dayton + otherErrorArr[m] : otherErrorName += otherErrorArr[m];
			});
			$.fn.message({
				type : "error",
				msg : otherErrorName + "属性的other值不能为空！",
				existTime : "20000"
			});
			return null;
		}
	}
	// 提交验证（必填和other）end
	return arr;
};
// SKU属性获取方法
var skuDataGet = function() {
	var arr = [], skuListObj = $('#skuVariantList'), requitedIdArr = [], requitedSkuHave = 1;
	$('#skuAttribute table tr').each(function() {
		if ($(this).find('span[data-names="attrNames"]').attr('data-requited') == 'y') {
			requitedIdArr.push($(this).find('span[data-names="attrNames"]').attr('id'));
		}
	});
	if (requitedIdArr.length != 0) {
		$(requitedIdArr).each(function(i) {
			if ($(skuListObj).find('td[pid="' + requitedIdArr[i] + '"]').length == 0) {
				requitedSkuHave = 0;
			}
		})
	}
	if (requitedSkuHave == 0) {
		$.fn.message({
			type : "error",
			msg : "必选变种属性未选择！"
		});
		return null;
	}
	var allIpmSkuStock;
	if ($(skuListObj).find('input[data-names="ipmSkuStock"]').length > 0) {
		allIpmSkuStock = 0;
		$(skuListObj).find('input[data-names="ipmSkuStock"]').each(function() {
			allIpmSkuStock += $(this).val();
		});
		if (allIpmSkuStock == 0) {
			$.fn.message({
				type : "error",
				msg : "变种库存量总和不能为0"
			});
			return null;
		}
	}
	$(skuListObj).find('tr[data-name="skuProperty"]').each(function() {
		id = '';
		var ipmSkuStock = $(this).find('input[data-names="ipmSkuStock"]').val(), skuPrice = $(this).find('input[data-names="skuPrice"]').val(), skuCode = $(this).find('input[data-names="skuCode"]').val(), skuStock = '', aeopSKUProperty = [];
		if (ipmSkuStock == '' || ipmSkuStock == undefined)
			ipmSkuStock = 0;
		ipmSkuStock == 0 ? skuStock = false : skuStock = true;
		$(this).find('td[data-names="property"]').each(function() {
			var propertyValueId = parseInt($(this).attr('cid')), skuPropertyId = parseInt($(this).attr('pid')), customizedName = $(this).attr('customizedName'), customizedPic = $(this).attr('customizedPic'), skuImgObj = $('#colorsImg' + skuPropertyId);
			if (customizedPic == 1 || customizedName == 1) {
				var skuImageObj = $(skuImgObj).find('td[cid="' + propertyValueId + '"]').closest('tr'), skuImage = $(skuImageObj).find('img').attr('src'), propertyValueDefinitionName = $.trim($(skuImageObj).find('input[data-names="propertyValueDefinitionName"]').val());
				if (propertyValueDefinitionName == undefined)
					propertyValueDefinitionName = '';
				if (skuImage == undefined)
					skuImage = '';
				if (customizedPic == 1 && customizedName == 1) {
					var obj = {
						propertyValueId : propertyValueId,
						skuImage : skuImage,
						propertyValueDefinitionName : propertyValueDefinitionName,
						skuPropertyId : skuPropertyId
					};
				}
				if (customizedPic == 0 && customizedName == 1) {
					var obj = {
						propertyValueId : propertyValueId,
						propertyValueDefinitionName : propertyValueDefinitionName,
						skuPropertyId : skuPropertyId
					};
				}
				if (customizedPic == 1 && customizedName == 0) {
					var obj = {
						propertyValueId : propertyValueId,
						skuImage : skuImage,
						propertyValueDefinitionName : propertyValueDefinitionName,
						skuPropertyId : skuPropertyId
					};
				}
			} else {
				var obj = {
					propertyValueId : propertyValueId,
					skuPropertyId : skuPropertyId
				};
			}
			aeopSKUProperty.push(obj);
			id == '' ? id = skuPropertyId + ":" + propertyValueId : id += ";" + skuPropertyId + ":" + propertyValueId;
		});
		ipmSkuStock = parseInt(ipmSkuStock);
		var obj = {
			id : id,
			ipmSkuStock : ipmSkuStock,
			skuPrice : skuPrice,
			skuStock : skuStock,
			aeopSKUProperty : aeopSKUProperty,
			skuCode : skuCode
		};
		arr.push(obj);
	});
	return arr;
};
// 数据回填（编辑用到）
var pushSmtData = function(attrArr, skuArr) {
	var pageSku = [];
	var skuAttrTd = $('#skuAttribute').find('table tr td:first-child span:nth-child(2)');
	$.each(skuAttrTd, function(i, j) {
		if ($(j).attr('id'))
			pageSku.push($(j).attr('id'));
	})
	if (attrArr != null) {
		var otherVal = '';
		$.each(attrArr, function(i, j) {
			var attrValueId = attrArr[i].attrValueId, attrNameId = attrArr[i].attrNameId, attrName = attrArr[i].attrName, attrValue = attrArr[i].attrValue;
			if (attrNameId != undefined) {
				var obj = $('#productAttribute').find('span[id="' + attrNameId + '"]'), type = $(obj).attr('data-type'), moreattribute = $(obj).closest('td').next().find('select').attr('moreattribute'), tr = $(obj).closest('tr');
				if (moreattribute == 1) {
					var arr = childAttributeList(attrNameId, attrValueId), str = newAttrList(arr);
					if (str != '' && str != undefined) {
						var $Str = $(str);
						tr.after($Str);
						$Str.find('.chosen-select').chosen({
							search_contains : true
						});// 注册插件
						tr.next().attr('data-names', 'newTr');
					}
				}
				if (type == 'select') {
					if (attrValue != undefined)
						otherVal = attrValue;
					if (attrValueId != undefined) {
						var option = $(obj).closest('td').next().find('option[data-cid="' + attrValueId + '"]');
						var text = option.text();
						option.closest('select').val(text);
						// 配置回选搜索插件
						$(obj).closest('td').next().find('option[data-cid="' + attrValueId + '"]:first').attr('selected', 'selected');// 先给select选中的option设置selected状态
						$(".chosen-select").trigger("chosen:updated");// 再给搜索插件回选
						// 配置回选搜索插件end
						if (attrValueId == 4) {
							var objOther = option.closest('select');
							otherClickShowIpt(objOther);
							option.closest('td').find('input[data-names="otherIpt"]').val(otherVal);
						}
					}

				}
				if (type == 'checkbox' || type == 'radio') {
					if (attrValue != undefined || attrValue != null)
						otherVal = attrValue;
					tr.find('input[data-cid="' + attrValueId + '"]').click();
					if (attrValueId == 4)
						tr.find('input[data-cid="' + attrValueId + '"]').closest('label').next().val(otherVal);
				}
				if (type == 'text') {
					if (attrValue) {
						var arr = attrValue.split(' ');
						if (arr.length == 2) {
							tr.find('select[data-names="units"]').val(arr[1]);
							if (tr.find('select[data-names="units"]').val() == arr[1])
								attrValue = arr[0];
						}
						tr.find('input[type="text"]').val(attrValue);
					}
				}
			} else if (attrName != undefined) {
				var str = '<div data-names="otherAttr" class="mBottom5"><span class="serial" style="margin-right:10px;"></span><input type="text" value="' + attrName + '" class="otherAttrFy" placeholder="属性名 - 例如：Color" maxLength="40"> ：<input type="text" value="' + attrValue + '" class="mRight10 otherAttrFy" placeholder="属性值 - 例如：Red" maxLength="70"><span class="glyphicon glyphicon-remove" style="cursor:pointer" data-names="otherAttrRemove"></span></div>';
				if ($('#otherAttr').find('div[data-names="errorNum"]').length > 0) {
					$('#otherAttr').find('div[data-names="errorNum"]').before(str);
				} else {
					$('#otherAttr').find('button').before(str);
				}
			}
		})
		$('#otherAttr').find('input').each(function() {
			var obj = $(this);
			strTesting(obj, 'otherAttr');
			otherAttrNumTesting();
		});
	}
	if (skuArr != null) {
		$.each(skuArr, function(i, j) {
			skuArr[i].aeopSKUPropertyNew = {};
			var property = skuArr[i].aeopSKUProperty;
			if (skuArr[i]['aeopSKUProperty']) {
				$.each(property, function(m, n) {
					var id = property[m].propertyValueId, pid = property[m].skuPropertyId, obj = $('#skuAttribute').find('input[data-cid="' + id + '"][pid="' + pid + '"]'), customizedName = $('#skuAttribute').find('span[id="' + pid + '"]').attr('customizedName'), customizedPic = $('#skuAttribute').find('span[id="' + pid + '"]').attr('customizedPic');
					skuArr[i].aeopSKUPropertyNew[pid] = id;
					if (obj[0] != null && !obj[0].checked)
						obj.click();
					if (customizedName == 1 || customizedPic == 1) {
						var url = property[m].skuImage, imgName = property[m].propertyValueDefinitionName;
						$('#colorsImg' + pid).find('td[cid="' + id + '"]').closest('tr').find('input').val(imgName);
						if (customizedPic == 1 && url != '' && url != undefined)
							skuImg(id, url);
					}
				})
			}
		})
		$.each(skuArr, function(i, j) {
			var ipmSkuStock = skuArr[i].ipmSkuStock, skuPrice = skuArr[i].skuPrice, skuCode = skuArr[i].skuCode, idNew = skuArr[i].aeopSKUPropertyNew, pushId = 'trID';
			$.each(pageSku, function(k, g) {
				if (idNew[pageSku[k]] != undefined)
					pushId += idNew[pageSku[k]];
			})
			var trObj = $('#skuVariantList tr[pushId="' + pushId + '"]');
			$(trObj).find('input[data-names="skuPrice"]').val(skuPrice);
			$(trObj).find('input[data-names="ipmSkuStock"]').val(ipmSkuStock);
			$(trObj).find('input[data-names="skuCode"]').val(skuCode);
		})

		// 特殊处理，没有sku变种时，设置单价个库存============================================
		if (skuArr != null && skuArr.length == 1) {
			for (var i = 0; i < skuArr.length; i++) {
				var obj = skuArr[i];
				if (obj != null) {
					var aeopSKUProperty = obj.aeopSKUProperty;
					if (aeopSKUProperty != null && aeopSKUProperty.length == 0) {
						$("#ipmSkuStock").val($.trim(obj.ipmSkuStock));
						$("#skuPrice").val($.trim(obj.skuPrice));
						$("#skuCode").val($.trim(obj.skuCode));
					}
				}
			}
		}

		propertyValueTesting();
		skuCodeTesting();
	}
};
// 类目数据
var newArr = '${list}';

// 类目html生成
var categoryHtml = function(arr) {
	var str = '';
	for ( var i in arr) {
		str += '<div class="categoryDiv"><span class="categoryNames" categoryId="' + arr[i].categoryId + '" title="' + arr[i].nameZh + '(' + arr[i].nameEn + ')">' + arr[i].nameZh + '</span>';
		if (arr[i].isleaf == 0) {
			str += '<span class="glyphicon glyphicon-chevron-right" data-isleaf="' + arr[i].isleaf + '"></span></div>';
		} else {
			str += '<span class="glyphicon glyphicon-chevron-right" data-isleaf="' + arr[i].isleaf + '" style="display:none;"></span></div>';
		}

	}
	return str;
};
// 类目显示
var categoryShow = function(arr, obj) {
	var str = categoryHtml(arr);
	if (obj == '' || obj == undefined) {
		$('#categoryChoose').find('div.categoryChooseInDiv').hide();
		$('#categoryChoose').find('div.categoryChooseInDiv div.categoryList').empty();
		$('#categoryChoose').find('div.categoryChooseInDiv div.serch input').val('');
		obj = $('#categoryChoose').find('div.categoryChooseInDiv:first').show();
		obj = $('#categoryChoose').find('div.categoryChooseInDiv:first div.categoryList').html(str);
		$('.categoryChooseCrumbs').find('span').each(function() {
			if ($(this).attr('data-level') != 1) {
				$(this).empty();
			} else {
				$(this).html('未选择分类');
			}
		});
	} else {
		/*
		 * $(obj).next().empty(); $(obj).next().nextAll().hide();
		 * $(obj).next().nextAll().empty(); $(obj).next().html(str);
		 * $(obj).next().show();
		 */
		$(obj).next().find('div.categoryList').empty();
		$(obj).next().find('div.serch input').val('');
		$(obj).next().nextAll().hide();
		$(obj).next().nextAll().find('div.categoryList').empty();
		$(obj).next().nextAll().find('div.serch input').val('');
		$(obj).next().find('div.categoryList').html(str);
		$(obj).next().show();
	}
};
// 类目项点击事件
$(document).on('click', '.categoryDiv', function() {
	// 添加背景色
	$(this).closest('div.categoryChooseInDiv').find('.categoryDiv').removeClass('bgColor5');
	$(this).addClass('bgColor5');

	var isleaf = $(this).find('span.glyphicon').attr('data-isleaf'), obj = $(this).closest('div.categoryChooseInDiv'), names = $(this).find('span.categoryNames').attr('title'), id = $(this).find('span.categoryNames').attr('categoryId'), level = $(obj).attr('data-level');
	// edit by fuyi 2015.5.5
	/*
	 * if(id == 200003656 || id == 4406 || id == 200003561 || id == 200001086 ||
	 * id == 200001680 || id == 5090301 || id == 200003950 || id == 200001076 ||
	 * id == 200001080 || id == 200000970 || id == 1501 || id == 320 || id ==
	 * 100001205 || id == 1204){ $.fn.message({type:"warning",msg:"发布<span
	 * style='color:red'>"+names +"</span>类产品需要到速卖通后台授权，否则产品会发布失败！",existTime:"10000"}); };
	 */
	// editEnd
	// 判断有没子集
	if (isleaf == 0) {
		$('.selectCategoryId').removeClass('selectCategoryId');
		$(this).addClass('selectCategoryId');

		$.ajax({
			type : 'POST',
			async : false,
			url : 'smtCategory/list.json',
			data : {
				pcid : id
			},
			dataType : 'json',
			success : function(data) {
				categoryShow(data, obj);
			}
		});

	} else {
		// $(this).closest('div.categoryChooseInDiv').find('.categoryDiv').removeClass('selectCategoryId');
		$('.selectCategoryId').removeClass('selectCategoryId');
		$(this).addClass('selectCategoryId');
		$(obj).nextAll().hide();
		$(obj).nextAll().find('div.categoryList').empty();
	}
	// 生成路径
	if (level == 1) {
		var str = '<span id="' + id + '">' + names + '</span>';
	} else {
		var str = '<span id="' + id + '">&nbsp;>&nbsp;' + names + '</span>';
	}
	$('.categoryChooseCrumbs').find('span[data-level="' + level + '"]').html(str);
	$('.categoryChooseCrumbs').find('span[data-level="' + level + '"]').nextAll().empty();

});

$(document).on('click', '.categoryModalShow', function() {
	$('#categoryChoose').modal('show');
});

// 显示从空间选择图片的窗口
function showImgSpaceFrame() {
	$("#myFrame").attr("src", 'album/selectImg.htm');
	$('#loading').modal('show');
}

// 显示从空间选择图片的窗口-sku图片
function showImgSpaceFrame2(skuImgId) {
	var param = "";
	if ($.trim(skuImgId) != "") {
		param = "?skuImgId=" + skuImgId;
	}
	if ("0" == skuImgId) {
		$("#smtPhotoRoomInsertTheWayBox").show();
	} else {
		$("#smtPhotoRoomInsertTheWayBox").hide();
	}

	$("#myFrame2").attr("src", 'album/selectImg.htm' + param);
	$('#loading').modal('show');
}

// 显示从图片银行选择图片的窗口
function showPhotoBankFrame(shopId) {
	var shopId = $("#shopId").val();
	if (shopId) {
		$("#photoBankFrame").attr("src", 'photoBank/selectImg.htm?shopId=' + shopId);
		$('#loading').modal('show');
	} else {
		$.fn.message({
			type : "error",
			msg : "请先选择店铺！"
		});
	}
}

// 显示从图片银行选择图片的窗口-sku图片
function showPhotoBankFrame2(shopId, skuImgId) {
	var shopId = $("#shopId").val();
	if (shopId) {
		var param = "";
		if ($.trim(skuImgId) != "") {
			param = "&skuImgId=" + skuImgId;
		}
		if ("0" == skuImgId) {
			$("#smtPhotoBankInsertTheWayBox").show();
		} else {
			$("#smtPhotoBankInsertTheWayBox").hide();
		}

		$("#photoBankFrame2").attr("src", 'photoBank/selectImg.htm?shopId=' + shopId + param);
		$('#loading').modal('show');
	} else {
		$.fn.message({
			type : "error",
			msg : "请先选择店铺！"
		});
	}
}
// 主图调用
function hideImgSpaceFrame() {
	$('#loading').modal('hide');
	$("#selectImgFromSpace").modal("show");
}
// sku用于图片空间调用-sku图片
function hideImgSpaceFrame2() {
	$('#loading').modal('hide');
	$("#selectImgFromSpace2").modal("show");
}
function hidePhotoBankFrame() {
	$('#loading').modal('hide');
	$("#selectImgFromPhotoBank").modal("show");
}
function hidePhotoBankFrame2() {
	$('#loading').modal('hide');
	$("#selectImgFromPhotoBank2").modal("show");
}
// 空间图片处理，从子窗口中得到选中的图片地址
function showSelectImgFromSpace() {
	var selImg = document.getElementById('myFrame').contentWindow.getSelectImg();

	if (dxmState != 'draft') {// 草稿箱
		var remainNum = maxUploadNum - imgTotalNum;
		if (selImg.length + imgTotalNum > maxUploadNum) {
			remainNum = remainNum < 0 ? 0 : remainNum;
			$.fn.message({
				type : "success",
				msg : "最大支持" + maxUploadNum + "张图片,上传成功" + remainNum + "张!"
			});
		}
		remainNum = selImg.length > remainNum ? remainNum : selImg.length;
		for (var i = 0; i < remainNum; i++) {
			// 生成展示图片
			var imgUrl = getPicRealUrl(selImg[i]);
			showImg('', imgUrl);
		}
		;

		$("#curImgNum").text(imgTotalNum);
	} else {
		var n = $("input[name='selectedImg']:checked").length;
		var remainNum = maxUploadNum - n;
		if (selImg.length + n > maxUploadNum) {
			remainNum = remainNum < 0 ? 0 : remainNum;
			$.fn.message({
				type : "success",
				msg : "最大支持" + maxUploadNum + "张图片,上传成功" + remainNum + "张!"
			});
		}
		remainNum = selImg.length > remainNum ? remainNum : selImg.length;
		for (var i = 0; i < remainNum; i++) {
			// 生成展示图片
			var imgUrl = getPicRealUrl(selImg[i]);
			showImg('', imgUrl, 'myj-show', true);
		}
		;
	}

	$('#selectImgFromSpace').modal('hide');
}

// 空间图片处理，从子窗口中得到选中的图片地址-sku图片
/* 2017.3.4 byzym 添加图片排版 */
function showSelectImgFromSpace2(obj) {
	var storedValueImg = $(obj).closest('.modal-footer').find('div').find('label:first').is('.insertTheWayClick');
	var selImg = document.getElementById('myFrame2').contentWindow.getSelectImg();
	var skuImgId = document.getElementById('myFrame2').contentWindow.getSkuImgId();
	if ($.trim(skuImgId) != "" && skuImgId != "0") {
		// sku图片上传
		var remainNum = 1;
		if (selImg.length > 1) {
			remainNum = remainNum < 0 ? 0 : remainNum;
		}
		remainNum = selImg.length > remainNum ? remainNum : selImg.length;
		for (var i = 0; i < remainNum; i++) {
			// sku图片上传
			var imgUrl = getPicRealUrl(selImg[i]);
			skuImg(skuImgId, imgUrl);
		}
	} else if (skuImgId == "0") {
		var imgHtml = '';
		for (var i = 0; i < selImg.length; i++) {
			// sku图片上传
			var imgUrl = getPicRealUrl(selImg[i]);
			imgHtml += '<img src="' + imgUrl + '"/>';
		}
		if (storedValueImg) {
			imgHtml = '<p style="margin:0;display: block;width: 100%;">' + imgHtml + '</p>';
		}
		if (editorInfo) {
			insertEditorData(editorInfo.editorId, imgHtml);
			editorInfo = null;
		}
	}

	$('#selectImgFromSpace2').modal('hide');
}

// 图片银行图片处理，从子窗口中得到选中的图片地址
function showSelectImgFromPhotoBank() {
	var selImg = document.getElementById('photoBankFrame').contentWindow.getSelectImg();

	if (dxmState != 'draft') {// 草稿箱
		var remainNum = maxUploadNum - imgTotalNum;
		if (selImg.length + imgTotalNum > maxUploadNum) {
			remainNum = remainNum < 0 ? 0 : remainNum;
			$.fn.message({
				type : "success",
				msg : "最大支持" + maxUploadNum + "张图片,上传成功" + remainNum + "张!"
			});
		}
		remainNum = selImg.length > remainNum ? remainNum : selImg.length;
		for (var i = 0; i < remainNum; i++) {
			// 生成展示图片
			var imgUrl = getPicRealUrl(selImg[i]);
			showImg('', imgUrl);
		}

		$("#curImgNum").text(imgTotalNum);
	} else {
		var n = $("input[name='selectedImg']:checked").length;
		var remainNum = maxUploadNum - n;
		if (selImg.length + n > maxUploadNum) {
			remainNum = remainNum < 0 ? 0 : remainNum;
			$.fn.message({
				type : "success",
				msg : "最大支持" + maxUploadNum + "张图片,上传成功" + remainNum + "张!"
			});
		}
		remainNum = selImg.length > remainNum ? remainNum : selImg.length;
		for (var i = 0; i < remainNum; i++) {
			// 生成展示图片
			var imgUrl = getPicRealUrl(selImg[i]);
			showImg('', imgUrl, 'myj-show', true);
		}
	}

	$('#selectImgFromPhotoBank').modal('hide');
}

// 图片银行图片处理，从子窗口中得到选中的图片地址
/* 2017.3.3 by zym 增加图片排版 */
function showSelectImgFromPhotoBank2(obj) {
	var storedValue = $(obj).closest('.modal-footer').find('div').find('label:first').is('.insertTheWayClick');
	var selImg = document.getElementById('photoBankFrame2').contentWindow.getSelectImg();
	var skuImgId = document.getElementById('photoBankFrame2').contentWindow.getSkuImgId();
	if ($.trim(skuImgId) != "" && skuImgId != "0") {
		// sku图片上传
		var remainNum = 1;
		if (selImg.length > 1) {
			remainNum = remainNum < 0 ? 0 : remainNum;
		}
		remainNum = selImg.length > remainNum ? remainNum : selImg.length;
		for (var i = 0; i < remainNum; i++) {
			// sku图片上传
			var imgUrl = getPicRealUrl(selImg[i]);
			skuImg(skuImgId, imgUrl);
		}
	} else if (skuImgId == "0") {
		var imgHtml = '';
		for (var i = 0; i < selImg.length; i++) {
			// sku图片上传
			var imgUrl = getPicRealUrl(selImg[i]);
			imgHtml += '<img src="' + imgUrl + '"/>';
		}
		if (storedValue) {
			imgHtml = '<p style="margin:0;display: block;width: 100%;">' + imgHtml + '</p>';
		}
		if (editorInfo) {
			insertEditorData(editorInfo.editorId, imgHtml);
			editorInfo = null;
		}
	}

	$('#selectImgFromPhotoBank2').modal('hide');
}

function selectMainImage() {
	var selImg = [];
	$('#mainImgModal .imgHomeList img').each(function() {
		selImg.push($(this).data("rel"));
	});
	var skuImgId = $("#skuImgId").val();

	if ($.trim(skuImgId) != "" && skuImgId != "0") {
		// sku图片上传
		var remainNum = 1;
		if (selImg.length > 1) {
			remainNum = remainNum < 0 ? 0 : remainNum;
		}
		remainNum = selImg.length > remainNum ? remainNum : selImg.length;
		for (var i = 0; i < remainNum; i++) {
			// sku图片上传
			var imgUrl = getPicRealUrl(selImg[i]);
			skuImg(skuImgId, imgUrl);
		}
	} else if (skuImgId == "0") {
		for (var i = 0; i < selImg.length; i++) {
			// sku图片上传
			var imgUrl = getPicRealUrl(selImg[i]);
			var imgHtml = '<img src="' + imgUrl + '"/>';
			if (editorInfo) {
				insertEditorData(editorInfo.editorId, imgHtml);
			}
		}
		editorInfo = null;
	}
	$("#skuImgId").val("");

	$('#mainImgModal').modal('hide');
}

// 网络图片处理
function downImgFromUrl() {
	var url = $.trim($("#netImgUrl").val());
	if (url == null || url == "") {
		$.fn.message({
			type : "error",
			msg : "图片地址不能为空！"
		});
		return false;
	}
	var urlArray = url.split("\n");
	// 去一下空格
	for ( var i in urlArray) {
		urlArray[i] = $.trim(urlArray[i]);
	}
	if (dxmState != 'draft') {// 草稿箱
		var remainNum = maxUploadNum - imgTotalNum;
		if (urlArray.length + imgTotalNum > maxUploadNum) {
			remainNum = remainNum < 0 ? 0 : remainNum;
			$.fn.message({
				type : "success",
				msg : "最大支持" + maxUploadNum + "张图片,您还能上传" + remainNum + "张!"
			});
		}
		remainNum = urlArray.length > remainNum ? remainNum : urlArray.length;
		for (var i = 0; i < remainNum; i++) {
			// 生成展示图片
			showImg("", urlArray[i]);
		}
		$("#curImgNum").text(imgTotalNum);
	} else {// 其他编辑页
		var n = $("input[name='selectedImg']:checked").length;
		var remainNum = maxUploadNum - n;
		if (urlArray.length + n > maxUploadNum) {
			remainNum = remainNum < 0 ? 0 : remainNum;
			$.fn.message({
				type : "success",
				msg : "最大支持" + maxUploadNum + "张图片,您还能上传" + remainNum + "张!"
			});
		}
		remainNum = urlArray.length > remainNum ? remainNum : urlArray.length;
		for (var i = 0; i < remainNum; i++) {
			// 生成展示图片
			showImg("", urlArray[i], 'myj-show', true);
		}
	}

	$("#imgModal").modal("hide");
	$("#netImgUrl").val("");
}

// 网络图片处理-sku图片
function downImgFromUrl2() {
	var url = $.trim($("#netImgUrl2").val());
	if (url == null || url == "") {
		$.fn.message({
			type : "error",
			msg : "图片地址不能为空！"
		});
		return false;
	}

	// 生成展示图片
	var skuPropertyCid = $("#skuPropertyCid").val();
	if ($.trim(skuPropertyCid) != "") {
		// sku图片上传
		skuImg(skuPropertyCid, url);
	}
	$("#skuPropertyCid").val("");

	$("#imgModal2").modal("hide");
	$("#netImgUrl2").val("");
}

// 图片数据结构
var imgData = {
	img : {
		head : '',
		tpl : '<li><div class="imgDivOut out">' +
		// '<div class="imgDivUp h20">'+
		// '<a href="javascript:void(0);" class="pull-left"
		// data-css="divPrev">前移</a>'+
		// '<a href="javascript:void(0);" class="pull-right"
		// data-css="divNext">后移</a></div>'+
		'<label class="#{isShow}"><input name="selectedImg" type="checkbox" #{imgChecked} value="#{urlPerfix}#{url}">　选择图片</label>' + '<div class="imgDivIn">' + '<img src="#{urlPerfix}#{url}" rel="#{urlPerfix}#{url}" class="imgCss" data-names="auxiliaryImg">' + '<div src="static/img/2023.png" class="imgTubiao"/></div>' + '<div class="imgSize"></div>' + '<div class="imgDivDown">' +
		// 图片编辑 fuyi 2015.7.16
		'<a href="javascript:void(0);" data-names="onLineHandleImg">在线美图</a><a href="javascript:void(0);" class="pull-right yiImg" onclick="delImg(this);">移除</a>' + '</div></li>',
		foot : '',
		data : [ {
			url : 'static/img/36.jpg'
		}, {
			url : 'static/img/36.jpg'
		}, {
			url : 'static/img/36.jpg'
		}, {
			url : 'static/img/36.jpg'
		}, {
			url : 'static/img/36.jpg'
		}, {
			url : 'static/img/36.jpg'
		}, {
			url : 'static/img/36.jpg'
		}, {
			url : 'static/img/36.jpg'
		}, {
			url : 'static/img/36.jpg'
		}, {
			url : 'static/img/36.jpg'
		} ]
	}
};
// 设置主图
function showImg(urlPerfix, url, isShow, selImg) {
	var imgChecked = '';
	if ($.trim(isShow) == "") {
		isShow = 'myj-hide';
		imgChecked = 'checked';
	}
	var tpl = '';
	// 去除空值
	if (url != '') {
		tpl += imgData['img']['tpl'].formatOther({
			'urlPerfix' : urlPerfix,
			'url' : url,
			'isShow' : isShow,
			'imgChecked' : imgChecked
		});
	}
	var div = $(tpl);
	$('#myj-drop').append(div);
	if ($.trim(isShow) == 'myj-hide' || selImg) {
		imgTotalNum += 1;
	}
	// 如果图片的张数等于最大张数时，隐藏点位图
	if (imgTotalNum >= maxUploadNum) {
		$("#img-kong").hide();
	}
	/** 注册拖拽方法 2015.3.31 by fuyi* */
	$('.myj-drop li').off();
	$('.myj-drop').sortable();
	/** 注册拖拽方法 2015.3.31 by fuyi end* */
	adjustMoveBtnShow();

	if (selImg) {
		// 选中添加的图片
		div.find(".imgDivIn").click();
	}

	// 测试
	getImgRealPX(urlPerfix + url);
	// 测试end
	return div;
}

function delImg(obj) {
	$(obj).closest('li').remove();
	imgTotalNum = $("#img_show input[name='selectedImg']:checked").length;
	$("#curImgNum").text(imgTotalNum);
	// 如果当前图片的张数小于最大允许张数，显示点位图
	if (imgTotalNum < maxUploadNum) {
		$("#img-kong").show();
	}
	// 调整移动按钮的显示与否
	adjustMoveBtnShow();
}
// 调整移动按钮的显示与隐藏
function adjustMoveBtnShow() {
	var divObjA = $('div.imgDivOut');
	for (var i = 0; i < divObjA.length - 1; i++) {
		$(divObjA[i]).find('a[data-css=divPrev]').show();
		$(divObjA[i]).find('a[data-css=divNext]').show();
	}
	$(divObjA[0]).find('a[data-css=divPrev]').hide();
	$(divObjA[divObjA.length - 1]).find('a[data-css=divNext]').hide();
}

// 做提交前的基本验证
function validation(op) {
	if (op != 3) {
		if ($.trim($("#parentSku").val()) == "") {
			$.fn.message({
				type : "error",
				msg : "ParentSKU不能为空！"
			});
			return false;
		}
	}
	// 如果要发布到线上，验证写在下面
	if (op == 2 || op == 3) {
		if ($.trim($("#name").val()) == "") {
			$.fn.message({
				type : "error",
				msg : "标题不能为空！"
			});
			return false;
		}
		if ($.trim($("#description").val()) == "") {
			$.fn.message({
				type : "error",
				msg : "描述不能为空！"
			});
			return false;
		}
		if (memoryData.length < 2) {
			$.fn.message({
				type : "error",
				msg : "标签不能少于两个！"
			});
			return false;
		}
		if (memoryData.length > 10) {
			$.fn.message({
				type : "error",
				msg : "标签不能多于10个！"
			});
			return false;
		}
		if ($("#goodsList input[name='sku']").length < 1) {
			if ($.trim($("#price").val()) == "") {
				$.fn.message({
					type : "error",
					msg : "价格不能为空！"
				});
				return false;
			}
			if ($.trim($("#inventory").val()) == "") {
				$.fn.message({
					type : "error",
					msg : "数量不能为空！"
				});
				return false;
			}
			var shippingTime = $.trim($("#productDeliveryTime").text());
			if (shippingTime == null || shippingTime == "" || shippingTime == "选择运送时间") {
				$.fn.message({
					type : "error",
					msg : "请选择或输入运送时间"
				});
				return false;
			}

			if ($.trim($("#shipping").val()) == "") {
				$.fn.message({
					type : "error",
					msg : "运费不能为空！"
				});
				return false;
			}
		}
	}
	return true;
}

var checkPackageType = function() {
	$("#packageType").each(function() {
		if (this.checked) {
			$("#packageType").val(1);
			$(".packageTypeHide").removeClass("myj-hide");

			selectProductUnit('100000014');// 包

			var unitId = $("#productUnit").val();
			var chName = $("select[name=productUnit] option[value=" + unitId + "]").attr("ch");
			$(".packageTypeUnit").text($.trim(chName));
		} else {
			$("#packageType").val(0);
			// $("#lotNum").val('');
			$(".packageTypeHide").addClass("myj-hide");

			var unitId = $("#productUnit").val();
			selectProductUnit(unitId);
		}
	});
};

var checkIsPackSell = function() {
	$("#isPackSell").each(function() {
		if (this.checked) {
			$("#isPackSell").val(1);
			$(".isPackSellHide").removeClass("myj-hide");
		} else {
			$("#isPackSell").val(0);
			$(".isPackSellHide").addClass("myj-hide");
		}
	});
};

var checkWholeSale = function() {
	$("#wholeSale").each(function() {
		if (this.checked) {
			$("#wholeSale").val(1);
			// $(".wholeSaleHide").removeClass("myj-hide");
			$(".wholeSaleHide input[type='text']").prop("disabled", false);
			var num = $('#bulkDiscount').val();
			if (num != '') {
				$('#skuVariantList table').find('input[data-names="skuPrice"]').each(function() {
					var skuprice = $(this).val(), bulkDiscount = (skuprice * (10 - num / 10) / 10).toFixed(2);
					$(this).closest('tr').find('span[data-names="bulkDiscount"]').html('$' + bulkDiscount);
				});
			}
		} else {
			$("#wholeSale").val(0);
			// $(".wholeSaleHide").addClass("myj-hide");
			$(".wholeSaleHide input[type='text']").prop("disabled", true);
			$('#skuVariantList table').find('span[data-names="bulkDiscount"]').html('--');
		}
	});
};

var setSkuPrice = function(value) {
	initPriceInfo1();
	var value = $("#batchSkuPrice").val();
	$("input[data-names='skuPrice']").val(value);
	pushPrice(priceComputing(value));
	// edit by fuyi
	var num = $('#bulkDiscount').val();
	if (num != '') {
		var newNum = '$' + (value * (1 - num / 100)).toFixed(2);
		$('#skuVariantList').find('span[data-names="bulkDiscount"]').html(newNum);
	}
};

var setSkuStock = function() {
	var value = $("#batchSkuStock").val();
	$("input[data-names='ipmSkuStock']").val(value);
};

var setSkuCode = function() {
	var smtProductCode = $("#smtProductCode").val();
	var obj = $("#skuVariantList tr[data-name=skuProperty]");
	if (obj.length > 0) {
		$.each(obj, function(index) {
			var value = smtProductCode;
			if ($.trim(value) == "") {
				value = "dxm";
			}
			var tr = $(obj).eq(index);
			tr.find('td[data-names="property"]').each(function() {
				var propertyPid = $(this).attr('pid'), propertyCid = $(this).attr('cid'), otherNameDivId = 'colorsImg' + propertyPid, propertyValue = '';
				if ($('#skuAttribute').find('#' + otherNameDivId).length > 0) {
					var otherName = $.trim($('#' + otherNameDivId + ' td[cid="' + propertyCid + '"]').next().find('input').val());
					if (otherName) {
						propertyValue = otherName.replace(/[ ]/g, '').replace('.', '-');
					} else {
						propertyValue = $(this).attr("data-value").replace(/[ ]/g, '').replace('.', '-');
					}
				} else {
					propertyValue = $(this).attr("data-value").replace(/[ ]/g, '').replace('.', '-');
				}
				value += "-" + propertyValue;

			});
			$(this).find('input[data-names="skuCode"]').val(value);
		});
	}
	$("#smtProductCodeModal").modal('hide');
};

var showSkuStock = function() {
	$("#smtProductCodeModal").modal("show");
};

// 自定义属性添加btn点击事件
var userSetAttr = function(obj) {
	var str = '<div data-names="otherAttr" class="mBottom5">' + '<span class="serial" style="margin-right:10px;"></span>' + '<input type="text" placeholder="属性名 - 例如：Color" maxLength="40" class="otherAttrFy"> ：' + '<input type="text" placeholder="属性值 - 例如：Red" maxLength="70" class="mRight10 otherAttrFy">' + '<span class="glyphicon glyphicon-remove" style="cursor:pointer"></span>' + '</div>';
	$(obj).before(str);
	otherAttrNumTesting();
};
$(document).on('click', 'div[data-names="otherAttr"] span.glyphicon-remove', function() {
	$(this).closest('div').remove();
	otherAttrNumTesting();
});

$(document).on('click', 'span.glyphicon-remove', function() {
	$(this).parent().remove();
});

// 选择店铺或初始化店铺
var selectShop = function(groupIds, ftId, ptId, flag) {
	var shopId = $("#shopId").val();
	// 初始化分组
	$("#groupIdSpan").html("未选择分组 ");
	$("#groupIds").val("");
	$("#groupId").val("");
	// 取消分组选中
	$("#treeB .chooseTree").html("");
	// 删除产品模板
	$(".productModuleTable").html("");
	// 切换店铺时，删除详情里的产品模板
	trimModules(flag);
	if ($.trim(shopId) == "") {
		$("#categoryHistoryId").html('<option value="">---- 请选择分类 ----</option>');
		$("#promiseTemplateId").html('<option value="">---- 请选择服务模板 ----</option>');
		$("#freightTemplateId").html('<option value="">---- 请选择运费模板 ----</option>');

		// 切换店铺时已选中的类目自动选中
		var historyCategoryId = $("#categoryId").val();
		if ($.trim(historyCategoryId) != "") {
			getNewCategoryHistory(historyCategoryId);
		}
		return;
	}

	// 历史记录类目
	$.ajax({
		type : 'POST',
		async : false,
		url : 'smtShopInfoSync/list.json',
		data : {
			shopId : shopId
		},
		dataType : 'json',
		success : function(data) {
			var promiseTemplateId = "";
			var promiseTemplateList = data.promiseTemplateList;
			var freightTemplateId = "";
			var freightTemplateList = data.freightTemplateList;
			var productGroupList = data.productGroupList;
			var historyList = data.historyList;
			var brandHistoryList = data.brandHistoryList;
			var categoryHistoryId = "";

			if (historyList != undefined) {
				categoryHistoryId = '<option value="">---- 请选择分类 ----</option>';
				for (var i = 0; i < historyList.length; i++) {
					var category = historyList[i];
					if (category != undefined) {
						var checkInfo = '';

						categoryHistoryId += '<option value="' + category.categoryId + '" ' + checkInfo + '>' + category.nameZh + '(' + category.nameEn + ')</option>';
					}
				}
				$("#categoryHistoryId").html(categoryHistoryId);
			}
			// 切换店铺时已选中的类目自动选中
			var historyCategoryId = $("#categoryId").val();
			if ($.trim(historyCategoryId) != "") {
				getNewCategoryHistory(historyCategoryId);
			}

			// 选择服务模板
			if (promiseTemplateList != undefined) {
				promiseTemplateId = '<option value="">---- 请选择服务模板 ----</option>';
				for (var i = 0; i < promiseTemplateList.length; i++) {
					var promise = promiseTemplateList[i];
					var checkInfo = '';
					if (ptId == promise.templateId) {
						checkInfo = 'selected';
					}
					promiseTemplateId += '<option value="' + promise.templateId + '" ' + checkInfo + '>' + promise.templateName + '</option>';
				}
				$("#promiseTemplateId").html(promiseTemplateId);
			}
			// 选择运费模板
			if (freightTemplateList != undefined) {
				freightTemplateId = '<option value="">---- 请选择运费模板 ----</option>';
				for (var i = 0; i < freightTemplateList.length; i++) {
					var freight = freightTemplateList[i];
					var checkInfo = '';
					if (ftId == freight.templateId) {
						checkInfo = 'selected';
					}
					freightTemplateId += '<option value="' + freight.templateId + '" ' + checkInfo + '>' + freight.templateName + '</option>';
				}
				$("#freightTemplateId").html(freightTemplateId);
			}
			// 历史品牌记录
			if (brandHistoryList) {
				$("#brandHistoryList").val(JSON.stringify(brandHistoryList));
			} else {
				$("#brandHistoryList").val("");
			}
			brandHistoryChange();// 店铺切换后品牌常用选项处理;
			// 设置店铺分组
			productGroupList = eval(productGroupList);
			if ($.trim(groupIds) == "") {
				groupIds = "";
			}
			// 选择产品分组
			setProductGroup(productGroupList, groupIds);

			// 设置信息模板
			setProductModule(shopId);

			// 设置店小秘模板
			setDxmProductModule(shopId);
		}
	});
};

// 设置产品分组信息
var setProductGroups = function(groupIds) {
	var shopId = $("#shopId").val();
	// 取消分组选中
	$("#treeB .chooseTree").html("");
	$.ajax({
		type : 'POST',
		async : false,
		url : 'smtShopInfoSync/list.json',
		data : {
			shopId : shopId
		},
		dataType : 'json',
		success : function(data) {
			var productGroupList = data.productGroupList;
			// 设置店铺分组
			productGroupList = eval(productGroupList);
			if ($.trim(groupIds) == "") {
				groupIds = "";
			}
			// 选择产品分组
			setProductGroup(productGroupList, groupIds);

			// 回填分组
			chooseGroupCheck();
		}
	});
};

// 设置信息模板
var setProductModule = function(shopId, moduleName) {
	$.ajax({
		type : 'GET',
		url : 'smtShopInfoSync/moduleList.htm',
		data : {
			shopId : shopId,
			moduleName : moduleName
		},
		dataType : 'html',
		success : function(data) {
			$(".productModuleTable").html(data);
		}
	});
};

var selectModuleName = function() {
	var moduleName = $("#moduleName").val();
	var shopId = $("#shopId").val();
	setProductModule(shopId, moduleName);
};

var insertInfoModule = function() {
	$(".productModuleTable").find('input[type="checkbox"]').each(function() {
		if (this.checked) {
			var id = $(this).val();
			var moduleType = $(this).attr("data-type");
			var moduleName = $(this).attr("data-name");
			var custom = "http://style.aliexpress.com/js/5v/lib/kseditor/plugins/widget/images/widget1.png?t=AEO9LPV";
			var relation = "http://style.aliexpress.com/js/5v/lib/kseditor/plugins/widget/images/widget2.png?t=AEO9LPV";
			var relatedProduct = "customText";
			if (moduleType == 'relation') {
				custom = relation;
				relatedProduct = "relatedProduct";
			}
			var str1 = escape('<kse:widget data-widget-type="' + relatedProduct + '" id="' + id + '" title="' + moduleName + '" type="' + moduleType + '"></kse:widget>'), str2 = '<img class="noImg" data-kse="' + str1 + '" src="' + custom + '"/>';
			if (editorInfo) {
				insertEditorData(editorInfo.editorId, str2);
			}
		}
	});
	editorInfo = null;

	// alert("插入产品信息模块");
	$("#categoryModules").modal('hide');
};

// 设置信息模板
var setDxmProductModule = function(shopId, moduleName) {
	$.ajax({
		type : 'GET',
		url : 'smtShopInfoSync/dxmModuleList.htm',
		data : {
			shopId : shopId,
			moduleName : moduleName
		},
		dataType : 'html',
		success : function(data) {
			$(".dxmProductModuleTable").html(data);
		}
	});
};

var selectDxmModuleName = function() {
	var moduleName = $("#dxmModuleName").val();
	var shopId = $("#shopId").val();
	setDxmProductModule(shopId, moduleName);
};

var insertInfoDxmModule = function() {
	$(".dxmProductModuleTable").find('input[type="checkbox"]').each(function() {
		if (this.checked) {
			var id = $(this).val();
			// 下面的别删，还有用
			/*
			 * var moduleType = $("#module"+id).attr("data-type"); var dxm =
			 * escape('<dxm:widget dxm-data-widget-type="dxmRelatedProduct"
			 * id="'+id+'" type="'+moduleType+'"></dxm:widget>'); var custom =
			 * "http://www.dianxiaomi.com/static/img/moban_custom.png"; var
			 * relation = "http://www.dianxiaomi.com/static/img/moban.png";
			 * if(moduleType == 1){ custom = relation; } var str = '<img
			 * class="dxmImg" data-kse="'+dxm+'" src="'+custom+'"/>';
			 */
			if (editorInfo) {
				insertEditorData(editorInfo.editorId, $("#module" + id).val());
			}
		}
	});
	editorInfo = null;

	// alert("插入产品信息模块");
	$("#categoryModules").modal('hide');
};

function checkSmtModule(showClass, hideClass) {
	$("." + showClass).removeClass("myj-hide");
	$("." + hideClass).addClass("myj-hide");
}

var uploadImg = function(type, cid, editorPic) {
	if (type == 1) {
		// $("#uploadImgInputDiv div[data="+cid+"].uploadSkuImg
		// input").trigger("click");
		imageUpload(cid);
	} else if (type == 2) {
		$("#skuPropertyCid").val(cid);
		$("#imgModal2").modal('show');
	} else if (type == 3) {
		showImgSpaceFrame2(cid);
	} else if (type == 4) {
		var shopId = $("#shopId").val();
		editorInfo = editorPic;
		showPhotoBankFrame2(shopId, cid);
	} else if (type == 5) {
		editorInfo = editorPic;
		showImgSpaceFrame2(cid);
	} else if (type == 6) {
		$("#skuImgId").val(cid);
		editorInfo = editorPic;
		showMainImage();
	}
};

var showInfoModule = function(editorMo) {
	var shopId = $("#shopId").val();
	if (shopId <= 0) {
		$.fn.message({
			type : "error",
			msg : "请先选择店铺！"
		});
		return;
	}
	editorInfo = editorMo;
	$("#categoryModules").modal('show');
};

var getDraftImgByParent = function() {
	var curImg = [];
	$("#img_show input[name='selectedImg']").each(function() {
		var rel = $(this).val();
		curImg.push(rel);
	});
	return curImg;
};

var showMainImage = function() {
	var curImg = [];
	$("#img_show input[name='selectedImg']").each(function() {
		var rel = $(this).val();
		curImg.push(rel);
	});
	if (curImg.length == 0 || dxmState != 'draft') {
		$.fn.message({
			type : "error",
			msg : "没有可引用的采集图片！"
		});
		return;
	}
	var imgDiv = '<div id="imgId" class="col-xs-3 p5 imgHomeDiv imgDivOut" style="width:185px;height:154px;margin-left:0;">' + '<label>' + '<div class="col-xs-12">' + '<input type="checkbox" class="imgHome" style="vertical-align:top;"> 选择图片' + '</div>' + '<div class="col-xs-12 imgHomeImg">' + '<div class="imgDivIn">' + '<img src="imgSrc" data-rel="imgRel" class="imgCss">' + '</div>' + '</div>' + '</label>' + '</div>';
	var htmlDiv = '';
	for (var i = 0; i < curImg.length; i++) {
		htmlDiv += imgDiv.replace('imgId', 'imgId' + i).replace('imgSrc', curImg[i]).replace('imgRel', curImg[i]);
	}
	$("#mainImageDiv").html(htmlDiv);
	$('.imgHomeList').html('');
	$('#mainImgModal').modal('show');
};

$(document).on('click', '.imgHome', function() {
	var name = $(this).closest('div.imgHomeDiv').attr('id'), src = $(this).closest('div.imgHomeDiv').find('img').attr('src'), rel = $(this).closest('div.imgHomeDiv').find('img').data('rel'), str = '<div class="p5 pull-left imgHomeSm" data-name="' + name + '"><span  class="aMakeRemoveBtn closeBadge"></span><div class="imgDivIn" style="width:50px;height:50px;"><img src="' + src + '" data-rel="' + rel + '" class="imgCss"></div></div>';
	if (this.checked) {
		$('.imgHomeList').append(str);

		$('.imgHomeList div').off();
		$('.imgHomeList').sortable();
	} else {
		$('.imgHomeSm').each(function() {
			if ($(this).attr('data-name') == name) {
				$(this).remove();
			}
		});
	}
});

$(document).on('click', '.closeBadge', function() {
	var div = $(this).closest('div.imgHomeSm'), id = $(div).attr('data-name');
	$(div).remove();
	$('#' + id).find('input[type=checkbox]').attr('checked', false);
});
// 运费模板
var downloadFreightTemplate = function() {
	var shopId = $("#shopId").val();
	if ($.trim(shopId) == "") {
		// $.fn.message({type:"error",msg:"请先选择店铺！"});
		return;
	}
	//
	$.ajax({
		type : 'POST',
		async : false,
		url : 'smtShopInfoSync/freightList.json',
		data : {
			shopId : shopId
		},
		dataType : 'json',
		success : function(data) {
			var freightTemplateId = "";
			var freightTemplateList = data.freightTemplateList;
			var id = $("#freightTemplateId").val();

			if (freightTemplateList != undefined) {
				freightTemplateId = '<option value="">---- 请选择运费模板 ----</option>';
				for (var i = 0; i < freightTemplateList.length; i++) {
					var freight = freightTemplateList[i];
					freightTemplateId += '<option value="' + freight.templateId + '">' + freight.templateName + '</option>';
				}
				$("#freightTemplateId").html(freightTemplateId);
				$("#freightTemplateId").val(id);
				$.fn.message({
					type : "success",
					msg : "同步运费模板成功!"
				});
			} else {
				$.fn.message({
					type : "error",
					msg : "同步运费模板失败!"
				});
			}
		}
	});
};

// 服务模板
var downloadPromiseTemplate = function() {
	var shopId = $("#shopId").val();
	if ($.trim(shopId) == "") {
		// $.fn.message({type:"error",msg:"请先选择店铺！"});
		return;
	}
	//
	$.ajax({
		type : 'POST',
		async : false,
		url : 'smtShopInfoSync/promiseList.json',
		data : {
			shopId : shopId
		},
		dataType : 'json',
		success : function(data) {
			var promiseTemplateId = "";
			var promiseTemplateList = data.promiseTemplateList;
			var id = $("#promiseTemplateId").val();

			if (promiseTemplateList != undefined) {
				promiseTemplateId = '<option value="">---- 请选择服务模板 ----</option>';
				for (var i = 0; i < promiseTemplateList.length; i++) {
					var promise = promiseTemplateList[i];
					promiseTemplateId += '<option value="' + promise.templateId + '">' + promise.templateName + '</option>';
				}
				$("#promiseTemplateId").html(promiseTemplateId);
				$("#promiseTemplateId").val(id);
				$.fn.message({
					type : "success",
					msg : "同步服务模板成功!"
				});
			} else {
				$.fn.message({
					type : "error",
					msg : "同步服务模板失败!"
				});
			}
		}
	});
};

// 同步尺码模板
var syncSizeChart = function() {
	var shopId = $("#shopId").val();
	var categoryId = $("#categoryId").val();
	if ($.trim(shopId) == "") {
		$.fn.message({
			type : "error",
			msg : "请先选择店铺！"
		});
		return;
	}
	if ($.trim(categoryId) == "") {
		$.fn.message({
			type : "error",
			msg : "请先选择类目！"
		});
		return;
	}

	$.ajax({
		type : 'POST',
		async : false,
		url : 'smtShopInfoSync/syncSizeChart.json',
		data : {
			shopId : shopId,
			categoryId : categoryId
		},
		dataType : 'json',
		success : function(data) {
			var sizeChartDiv = '<option value="">---- 请选择尺码模板 ----</option>';
			var code = data.code;
			if (code == -1) {
				$.fn.message({
					type : "error",
					msg : data.errMsg
				});
				// $("#sizechartId").addClass("myj-hide");
				$("#sizechartId").html(sizeChartDiv);
				return;
			} else if (code == 1) {
				// 不需要尺码模板
				// $("#sizechartId").addClass("myj-hide");
				$("#sizechartId").html(sizeChartDiv);
				return;
			} else if (code == 0) {
				// 类目需要尺码模板
				// $("#sizechartId").removeClass("myj-hide");
			}

			var sizeList = data.sizeList;
			var id = $("#sizechartId").val();

			if (sizeList != undefined) {
				for (var i = 0; i < sizeList.length; i++) {
					var sc = sizeList[i];
					sizeChartDiv += '<option value="' + sc.sizechartId + '">' + sc.name + '</option>';
				}
				$("#sizechartId").html(sizeChartDiv);
				$("#sizechartId").val(id);
				$.fn.message({
					type : "success",
					msg : "同步尺码模板成功!"
				});
			} else {
				$.fn.message({
					type : "error",
					msg : "同步尺码模板失败!"
				});
			}
		}
	});
};

// 下拉尺码模板
var downloadSizeChartList = function(sizechartId) {
	var shopId = $("#shopId").val();
	var categoryId = $("#categoryId").val();
	if ($.trim(shopId) == "") {
		// $.fn.message({type:"error",msg:"请先选择店铺！"});
		return;
	}
	if ($.trim(categoryId) == "") {
		// $.fn.message({type:"error",msg:"请先选择类目！"});
		return;
	}

	$.ajax({
		type : 'POST',
		async : false,
		url : 'smtShopInfoSync/sizeChartList.json',
		data : {
			shopId : shopId,
			categoryId : categoryId
		},
		dataType : 'json',
		success : function(data) {
			var sizeChartDiv = '<option value="">---- 请选择尺码模板 ----</option>';
			var code = data.code;
			if (code == -1) {// 系统错误
				// 不需要尺码模板
				// $("#sizeChartTr").addClass("myj-hide");
				$("#sizechartId").html(sizeChartDiv);

				// 编辑时，有尺码，店小秘没记录
				if ($.trim(sizechartId) != "" && sizechartId != -1) {
					setEditSizechartId(sizechartId);
				}
				return;
			} else if (code == 1) {// 不需要尺码模板
				// $("#sizeChartTr").addClass("myj-hide");
				$("#sizechartId").html(sizeChartDiv);

				// 编辑时，有尺码，店小秘没记录
				if ($.trim(sizechartId) != "" && sizechartId != -1) {
					setEditSizechartId(sizechartId);
				}
				return;
			} else if (code == 0) {
				// 类目需要尺码模板
				// $("#sizeChartTr").removeClass("myj-hide");
			}

			var sizeList = data.sizeList;

			if (sizeList != undefined) {
				for (var i = 0; i < sizeList.length; i++) {
					var sc = sizeList[i];
					sizeChartDiv += '<option value="' + sc.sizechartId + '">' + sc.name + '</option>';
				}
			}
			$("#sizechartId").html(sizeChartDiv);
			// sizechartId 不为空
			if ($.trim(sizechartId) != "" && sizechartId != -1) {
				// 编辑时，有尺码，店小秘没记录
				$("#sizechartId").val(sizechartId);
			}
		}
	});
};

// 编辑时，有尺码，店小秘没记录
var setEditSizechartId = function(sizechartId) {
	var obj = $('#sizechartId option[value="' + sizechartId + '"]');
	// 如果下拉列表存在则直接选中
	if (obj.text() != undefined && obj.text() != "") {
		$('#sizechartId option[value=""]').remove();
		$("#sizechartId").val(sizechartId);
	} else {
		var sizeChartDiv = '<option value="' + sizechartId + '">尺码id：' + sizechartId + '不存在，请同步尺码模板</option>';
		$("#sizechartId").html(sizeChartDiv);
		$("#sizechartId").val(sizechartId);
	}
};

/**
 * 选择产品分类历史记录
 */
var selectHistoryCategory = function(e) {
	var categoryId = $(e).val();
	if ($.trim(categoryId) == "") {

	} else {
		processSelectHistoryCategory(categoryId, true);
	}
};

function processSelectHistoryCategory(categoryId, initProduct) {
	// 清除请选择
	$('#categoryHistoryId option[value=""]').remove();

	$.ajax({
		type : 'POST',
		async : false,
		url : 'smtCategory/getHistoryCategory.json',
		data : {
			categoryId : categoryId
		},
		dataType : 'json',
		success : function(data) {
			if (initProduct) {
				initEditProduct('', '', categoryId);
				priceAndStock();
			}
			initCategory(data);
		}
	});
}

/** *************************产品分组 start*********************** */

// 选择产品分组
var setProductGroup = function(productGroupList, pushStr) {
	if (productGroupList != undefined) {
		arr = productGroupList;
		$.fn.myj_tree.chooseTreeInit('treeB', arr, sitt, pushStr, 0);
	}
};

/**
 * 选择分组
 */
var chooseProductGroup = function() {
	var shopId = $("#shopId").val();
	if ($.trim(shopId) == "") {
		$.fn.message({
			type : "error",
			msg : "请选择速卖通店铺!"
		});
		return;
	}
	$('#productGroupChoose').modal('show');
};
/**
 * 确认分组
 */
var chooseGroupCheck = function() {
	var group = $.fn.myj_tree.chooseTreeCheckGet('treeB');
	var groupIdSpan = "";
	var groupIds = "";
	var groupId = "";
	if (group != null && group.length > 0) {
		for (var i = 0; i < group.length; i++) {
			if (i > 0) {
				groupIdSpan += "、";
				groupIds += ",";
			}
			groupIdSpan += group[i].groupName;
			groupIds += group[i].groupId;
			groupId = group[i].groupId;
		}
		$("#groupIdSpan").html(groupIdSpan);
		$("#groupIds").val(groupIds);
		$("#groupId").val(groupId);
		$('#productGroupChoose').modal('hide');
	} else {
		$("#groupIdSpan").html("未选择分组 ");
		$("#groupIds").val("");
		$("#groupId").val("");
	}
};
/**
 * 确认分组
 */
var getGroupCheck = function() {
	var group = $.fn.myj_tree.chooseTreeCheckGet('treeB');
	var groupIds = "";
	if (group != null && group.length > 0) {
		for (var i = 0; i < group.length; i++) {
			if (i > 0) {
				groupIds += ",";
			}
			groupIds += group[i].groupId;
		}
	}
	return groupIds;
};
/** *************************产品分组 end*********************** */
/** ************************编辑初始化start********************** */
// 初始化类目
var initCategory = function(categoryList) {
	var pcid = "0";
	// 获取第一级
	$.ajax({
		type : 'POST',
		async : false,
		url : 'smtCategory/list.json',
		data : {
			pcid : pcid
		},
		dataType : 'json',
		success : function(data) {
			categoryShow(data);

			$(".productInfoModule .productInfoModule-content .category").html($(".categoryChooseCrumbs").html());
			categoryList = eval(categoryList);
			if (categoryList != undefined) {
				for (var i = categoryList.length - 1; i >= 0; i--) {
					var categoryId = categoryList[i];
					$(".categoryChooseOutDiv .categoryChooseInDiv span[categoryId=" + categoryId + "]").parent().click();
					if (i == 0) {
						$(".productInfoModule .productInfoModule-content .category").html($(".categoryChooseCrumbs").html());
					}
				}
			}
		}
	});
};

// 初始化属性
var initEditProduct = function(attrArr, skuArr, categoryId, sizechartId) {
	// 加载属性
	$.ajax({
		type : 'POST',
		async : false,
		url : 'smtCategory/attributeList.json',
		data : {
			categoryId : categoryId
		},
		dataType : 'json',
		success : function(data) {
			$("#categoryId").val(categoryId);
			attrArr = eval(attrArr);
			skuArr = eval(skuArr);
			// 填充产品属性
			showProductAttribute(data, true);

			// 填充sku属性
			pushSmtData(attrArr, skuArr);

			// 特殊处理，没有sku变种时，设置单价个库存
			if (skuArr != null && skuArr.length == 1) {
				for (var i = 0; i < skuArr.length; i++) {
					var obj = skuArr[i];
					if (obj != null) {
						var aeopSKUProperty = obj.aeopSKUProperty;
						if (aeopSKUProperty != null && aeopSKUProperty.length == 0) {
							$("#ipmSkuStock").val($.trim(obj.ipmSkuStock));
							$("#skuPrice").val($.trim(obj.skuPrice));
							$("#skuCode").val($.trim(obj.skuCode));
						}
					}
				}
			}

			// 类目尺码
			if (sizechartId) {
				downloadSizeChartList(sizechartId);
			}
		}
	});
};

// 选择模板后填充属性
var templateSetProduct = function(attrArr, categoryId) {
	var oldCategoryId = $("#categoryId").val();
	// 加载属性
	$.ajax({
		type : 'POST',
		async : false,
		url : 'smtCategory/attributeList.json',
		data : {
			categoryId : categoryId
		},
		dataType : 'json',
		success : function(data) {
			$("#categoryId").val(categoryId);

			attrArr = eval(attrArr);
			// 填充产品属性
			showProductAttribute(data, !(oldCategoryId == categoryId));

			// 填充sku属性
			pushSmtData(attrArr, null);
		}
	});
};

var showCategoryHistory = function(historyList, categoryId) {
	if ($.trim(historyList) != "") {
		historyList = eval(historyList);
		var categoryHistoryId = '<option value="">---- 请选择分类 ----</option>';
		for (var i = 0; i < historyList.length; i++) {
			var category = historyList[i];
			if (category != undefined) {
				var checkInfo = '';
				if (category.categoryId == categoryId) {
					checkInfo = 'selected';
				}
				categoryHistoryId += '<option value="' + category.categoryId + '" ' + checkInfo + '>' + category.nameZh + '(' + category.nameEn + ')</option>';
			}
		}
		$('#categoryHistoryId').html(categoryHistoryId);

	}
	if ($.trim(categoryId) != "") {
		getNewCategoryHistory(categoryId);
	}
};

/**
 * 选中类目
 */
var getNewCategoryHistory = function(categoryId) {
	var obj = $('#categoryHistoryId option[value="' + categoryId + '"]');

	// 如果历史列表存在则直接选中
	if (obj.text() != undefined && obj.text() != "") {
		$('#categoryHistoryId option[value=""]').remove();
		$("#categoryHistoryId").val(categoryId);
		return;
	}

	var categoryHistoryId = '';
	$.ajax({
		type : 'POST',
		async : false,
		url : 'smtCategory/getByCategoryId.json',
		data : {
			categoryId : categoryId
		},
		dataType : 'json',
		success : function(data) {
			if (data != null) {
				categoryHistoryId += '<option value="' + categoryId + '">' + data.nameZh + '(' + data.nameEn + ')</option>';
				$("#categoryHistoryId").append(categoryHistoryId);
				$("#categoryHistoryId").val(categoryId);
				$('#categoryHistoryId option[value=""]').remove();
			}
		}
	});
};

// 初始化店铺相关信息，服务模板、运费模板、分组
var initShopInfo = function(shopId, groupIds, freightTemplateId, promiseTemplateId) {
	if ($.trim(shopId) != "") {
		$("#shopId").val(shopId);
		selectShop(groupIds, freightTemplateId, promiseTemplateId, 1);
		chooseGroupCheck();
	}
};

// 初始化主图
var initMainImg = function(dxmState, imageURLs, draftImgUrl) {
	if (dxmState == 'draft') {
		// 设置采集箱主图
		if (draftImgUrl != null && draftImgUrl != "") {
			var extImgArray = draftImgUrl.split("|");
			var imgUrl = "";
			for ( var i in extImgArray) {
				imgUrl = getPicRealUrl(extImgArray[i]);
				// 生成展示图片
				showImg("", imgUrl, 'myj-show');
			}
		}

		// 设置采集箱选择图片
		$("#img_show input[name='selectedImg']").each(function() {
			var rel = $(this).val();
			if (imageURLs.indexOf(rel) != -1) {
				$(this).attr("checked", true);
				// 被选中就渲染图框的样式
				if ($(this).is(":checked")) {
					$(this).closest('.out').find('.imgDivIn').css({
						'border-color' : '#337ab7',
						'border-width' : '2px'
					});
				} else {
					$(this).closest('.out').find('.imgDivIn').css({
						'border-color' : '#ccc',
						'border-width' : '1px'
					});
				}
			}
		});
	} else {
		// 设置主图
		if (imageURLs != null && imageURLs != "") {
			var extImgArray = imageURLs.split(";");
			var imgUrl = "";
			for ( var i in extImgArray) {
				imgUrl = getPicRealUrl(extImgArray[i]);
				// 生成展示图片
				div = showImg("", imgUrl);
			}
		}
	}

	// 设置可上传图片总数，与当前已经上传数
	$("#maxImgNum").text(maxUploadNum);
	$("#curImgNum").text($("input[name='selectedImg']:checked").length);
};

// 主图选择图片
$(document).on('click', '#img_show input[name="selectedImg"]', function(event) {
	imgTotalNum = $("#img_show input[name='selectedImg']:checked").length;
	$("#curImgNum").text(imgTotalNum);
	if (imgTotalNum > maxUploadNum) {
		if (this.checked) {
			$.fn.message({
				type : "error",
				msg : "最多只能选择" + maxUploadNum + "张主图！"
			});
		}
		$(this).attr("checked", false);
		imgTotalNum = $("#img_show input[name='selectedImg']:checked").length;
		$("#curImgNum").text(imgTotalNum);
		return;
	}
	// 被选中就渲染图框的样式
	if ($(this).is(":checked")) {
		$(this).closest('.out').find('.imgDivIn').css({
			'border-color' : '#337ab7',
			'border-width' : '2px'
		});
	} else {
		$(this).closest('.out').find('.imgDivIn').css({
			'border-color' : '#ccc',
			'border-width' : '1px'
		});
	}
});

// 点击图片进行图片选择
$(document).on('click', '#img_show div[class="imgDivIn"]', function(event) {
	var show = $(this).closest('.imgDivOut').find('label').attr('class');
	if (show == 'myj-show') { // 只有有选择框的图片才可以选择
		$(this).closest('.imgDivOut').find('input[name="selectedImg"]').click();
	}
});

// 回显按钮值和下拉框
var setButton = function(reduceStrategy, wsValidNum, bulkOrder, bulkDiscount, isPackSell, addUnit, addWeight, baseUnit, packageType, lotNum, productUnit) {
	if ($.trim(productUnit) != "") {
		$("#productUnit").val(productUnit);
		selectProductUnit(productUnit);
	}

	// 有效期
	$("input[type=radio][name=reduceStrategy]").each(function() {
		if ($(this).val() == reduceStrategy) {
			$(this).attr("checked", "checked");
		}
	});

	// 有效期
	$("input[type=radio][name=wsValidNum]").each(function() {
		if ($(this).val() == wsValidNum) {
			$(this).attr("checked", "checked");
		}
	});

	// 是否批发。批发最小数量和批发折扣需同时有值或无值
	if ($.trim(bulkOrder) != "" && $.trim(bulkDiscount) != "" && bulkOrder != "0") {
		$("#bulkOrder").val(bulkOrder);
		$("#bulkDiscount").val(bulkDiscount);
		$("#bulkOrder").prop('disabled', false);
		$("#bulkDiscount").prop('disabled', false);
		// 选中批发
		$("input[type=checkbox][name=wholeSale]").each(function() {
			$(this).attr("checked", "checked");
			$("#wholeSale").val(1);
		});
		$(".wholeSaleHide").removeClass("myj-hide");
		// 设置变种的批发价
		$('input[name="bulkDiscount"]').keyup();
	}

	// 自定义计重
	if ($.trim(isPackSell) != "" && isPackSell == "1") {
		// 选中自定义计重
		$("input[type=checkbox][name=isPackSell]").each(function() {
			$(this).attr("checked", "checked");
			$("#isPackSell").val(1);
		});
		$("#addUnit").val(addUnit);
		$("#addWeight").val(addWeight);
		$("#baseUnit").val(baseUnit);
		$(".isPackSellHide").removeClass("myj-hide");
	}

	// 打包出售
	if ($.trim(packageType) != "" && packageType == "1") {
		// 选中打包出售
		$("input[type=checkbox][name=packageType]").each(function() {
			$(this).attr("checked", "checked");
			$("#packageType").val(1);
		});
		$("#lotNum").val(lotNum);
		checkPackageType();
	}
};

var setSkuPriceText = function() {
	$('input[data-names="skuPrice"]').keyup();
	$('div[data-names="volume"] input[type="text"]').focusout();
};

var setInput = function(deliveryTime, grossWeight, packageLength, packageWidth, packageHeight) {
	if ($.trim(deliveryTime) != "" && deliveryTime > 0) {
		$("#deliveryTime").val(deliveryTime);
	}
	if ($.trim(grossWeight) != "" && grossWeight > 0) {
		$("#grossWeight").val(grossWeight);
	}
	if ($.trim(packageLength) != "" && packageLength > 0) {
		$("#packageLength").val(packageLength);
	}
	if ($.trim(packageWidth) != "" && packageWidth > 0) {
		$("#packageWidth").val(packageWidth);
	}
	if ($.trim(packageHeight) != "" && packageHeight > 0) {
		$("#packageHeight").val(packageHeight);
	}

	// 设置input回显值
	setSkuPriceText();
};
/** ************************编辑初始化end********************** */

var selectCurUnit = function(unitId) {
	selectProductUnit(unitId);

	var packageType = $("#packageType").val();
	if (packageType == 1) {
		$(".packageTypeHide").removeClass("myj-hide");

		selectProductUnit('100000014');// 包

		var unitId = $("#productUnit").val();
		var chName = $("select[name=productUnit] option[value=" + unitId + "]").attr("ch");
		$(".packageTypeUnit").text($.trim(chName));
	}
};

// 设置计件单位
var selectProductUnit = function(unitId) {
	var chName = $("select[name=productUnit] option[value=" + unitId + "]").attr("ch");
	$(".chUnit").text($.trim(chName));
};
// 体积计算
$(document).on('focusout', 'div[data-names="volume"] input[type="text"]', function() {
	// $('div[data-names="volume"] input[type="text"]').focusout(function(){
	var leng = $('div[data-names="volume"]').find('input[name="packageLength"]').val(), wid = $('div[data-names="volume"]').find('input[name="packageWidth"]').val(), hei = $('div[data-names="volume"]').find('input[name="packageHeight"]').val();
	if (leng != '' && wid != '' && hei != '') {
		var volume = leng * wid * hei;
		$('div[data-names="volume"] span[data-names="volume"]').html(volume);
	} else {
		$('div[data-names="volume"] span[data-names="volume"]').html('0');
	}
});

// 实际收入计算
var priceComputing = function(num) {
	var newNum = '$' + parseFloat(num * 95 / 100).toFixed(2);
	return newNum;
};
var pushPrice = function(str) {
	$('#skuVariantList').find('span[data-names="skuPrice"]').each(function() {
		$(this).html(str);
	});
};

// 批发价计算
// 变种列表价格ipt的val变化算批发价
$(document).on('keyup', 'input[data-names="skuPrice"]', function() {
	var num = $(this).val();
	var price = priceComputing(num);
	var otherNum = $('#bulkDiscount').val();

	$(this).closest('tr').find('span[data-names="skuPrice"]').html(price);
	if (otherNum != '') {
		var bulkDiscount = (num * (10 - otherNum / 10) / 10).toFixed(2);
		$(this).closest('tr').find('span[data-names="bulkDiscount"]').html('$' + bulkDiscount);
	}
});
// 批发减免ipt的val变化算批发价
$(document).on('keyup', 'input[name="bulkDiscount"]', function() {
	var num = $(this).val();
	var price = $('#batchSkuPrice').val();
	if (num != '') {
		if (num % 10 == 0) {
			num = ((1 - num / 100) * 10).toFixed(0);
		} else {
			num = ((1 - num / 100) * 10).toFixed(1);
		}
		$('span[data-names="bulkDiscount"]').html(num);
		if (price != '') {
			price = '$' + (price * num / 10).toFixed(2);
			$('#skuVariantList').find('span[data-names="bulkDiscount"]').html(price);
		} else {
			$('#skuVariantList').find('span[data-names="bulkDiscount"]').html('--');
		}
	} else {
		$('span[data-names="bulkDiscount"]').html('--');
		if (price != '') {
			price = '$' + (price * 10 / 10).toFixed(2);
			$('#skuVariantList').find('span[data-names="bulkDiscount"]').html(price);
		} else {
			$('#skuVariantList').find('span[data-names="bulkDiscount"]').html('--');
		}
	}
	$('#skuVariantList').find('input[data-names="skuPrice"]').each(function() {
		var str = $(this).val();
		if (str != $('#batchSkuPrice').val() && str != '') {
			str = '$' + (str * (10 - $('#bulkDiscount').val() / 10) / 10).toFixed(2);
			$(this).closest('tr').find('span[data-names="bulkDiscount"]').html(str);
		}
	});
});

var jumpSourceUrl = function(obj) {
	var jumpUrl = $(obj).parent().prev().val();
	if ($.trim(jumpUrl) != "") {
		if (jumpUrl.indexOf("http") == -1 && jumpUrl.indexOf("HTTP") == -1 && jumpUrl.indexOf("https") == -1) {
			jumpUrl = "http://" + jumpUrl;
		}
		window.open(jumpUrl);
	}
};

var detailT = "";// 详情
var mobileDetailT = "";// 详情
// 一键翻译,翻译产品的名称和描述
function keyTranslate() {
	// 产品详细描述
	detailT = editorReplaceDisabledTag(editorReplaceAllBlank(smtStrHand.transitionHtml(getEditorData('myj-editor'))));
	mobileDetailT = editorReplaceDisabledTag(editorReplaceAllBlank(smtStrHand.transitionHtml(getEditorData('myj-editor-wireless'))));
	// console.log(detailT);
	// console.log(mobileDetailT);
	// 去掉全角字符
	trimAlt('myj-editor');
	trimAlt('myj-editor-wireless');

	trimIdAlt("subject");
	var subject = $.trim($("#subject").val());

	if (subject != "") {
		baiDuTranslate(subject, function(data) {
			if (data != "") {
				$("#subject").val(data);
				strTesting('', 'subjectTxtNum');
			}
		});
	}

	// 自定义属性
	var otherAttrFyArr = $(".otherAttrFy");
	var fyLength = otherAttrFyArr.length;
	for (var i = 0; i < fyLength; i++) {
		var attrValue = otherAttrFyArr.eq(i).val();
		setOtherAttrFy(fyLength, i, attrValue, otherAttrFyArr);
	}

	var splitStr = '|||';
	var detailStr = trimLabel(detailT, splitStr);
	var detailArr = detailStr.split(splitStr);
	detailArr = transateArrHandle(detailArr);
	for (var i = 0; i < detailArr.length; i++) {
		var s = detailArr[i];
		if ($.trim(s) != "") {
			setDetailTransate(s, i + 1 == detailArr.length);
		}
	}

	var mobileDetailStr = trimLabel(mobileDetailT, splitStr);

	var mobileDetailArr = mobileDetailStr.split(splitStr);
	mobileDetailArr = transateArrHandle(mobileDetailArr);
	for (var i = 0; i < mobileDetailArr.length; i++) {
		var s = mobileDetailArr[i];
		if ($.trim(s) != "") {
			setMobileDetailTransate(s, i + 1 == mobileDetailArr.length);
		}
	}
}

var setDetailTransate = function(s, t) {
	var now = s;
	baiDuTranslate(s, function(data, t) {
		if (data != "") {
			detailT = detailT.replace(now, data);
			// setKindeDetail(detailT);
			if (t)
				setEditorData('myj-editor', smtStrHand.unTransitionHtml(detailT));
		}
	}, t);
};
var setMobileDetailTransate = function(s, t) {
	var now = s;
	baiDuTranslate(s, function(data, t) {
		if (data != "") {
			mobileDetailT = mobileDetailT.replace(now, data);
			// setKindeDetail(detailT);
			/*
			 * ueSetHtml('myj-editor-wireless','')
			 * ueInsertHtml('myj-editor-wireless',ueUnTransitionHtml(mobileDetailT));
			 */
			if (t)
				setEditorData('myj-editor-wireless', smtStrHand.unTransitionHtml(mobileDetailT));
		}
	}, t);
};
// 获取标签中间的值
function trimLabel(s, splitStr) {
	var reg = /(<.*?>)/i;
	while (reg.test(s)) {
		var mStr = RegExp.$1;
		s = s.replace(mStr, splitStr);
	}
	return s;
}

var regP1 = / [a-zA-Z0-9_-]+=("([^\"]*[\u4e00-\u9fa5]+.*?)"|'([^\']*[\u4e00-\u9fa5]+.*?)')/ig;

// 获取标签中间的值
var replaceChars = {
	'，' : ',',
	'‘' : '\'',
	'’' : '\'',
	'“' : '"',
	'”' : '"',
	'；' : ';',
	'￥' : '$',
	'：' : ':',
	'。' : '.',
	'！' : '!',
	'（' : '(',
	'）' : ')',
	'？' : '?',
	'、' : ',',
	'—' : '-',
	'…' : '...',
	'\u3000' : ' ',
	' ' : ' '
};// ,'•':'.'
function trimAlt(id) {
	var str = editorReplaceDisabledTag(editorReplaceAllBlank(smtStrHand.transitionHtml(getEditorData(id))));

	var regexChars = new RegExp("(" + Object.keys(replaceChars).join('|') + ")", 'g');

	str = str.replace(regexChars, function(mChar) {
		return replaceChars[mChar];
	});

	// 去除标签属性值中文为空
	str = str.replace(regP1, '');

	// setKindeDetail(detailT);
	/*
	 * if(id == 'myj-editor-wireless'){ ueSetHtml(id,'')
	 * ueInsertHtml(id,ueUnTransitionHtml(str)); }else{
	 * ueSetHtml(id,ueUnTransitionHtml(str)); }
	 */
	// setEditorContent(id,'');
	setEditorData(id, smtStrHand.unTransitionHtml(str));
}

function trimIdAlt(id) {
	var value = $("#" + id).val();

	var regexChars = new RegExp("(" + Object.keys(replaceChars).join('|') + ")", 'g');

	value = value.replace(regexChars, function(mChar) {
		return replaceChars[mChar];
	});
	$("#" + id).val(value);
}
// 获取标签中间的值
function trimModules(flag) {
	if (flag != 1) {
		var reg = /(<kse:widget.*?><\/kse:widget>)/i;
		var detailT = editorReplaceDisabledTag(editorReplaceAllBlank(smtStrHand.transitionHtml(getEditorData('myj-editor'))));
		for (var i = 0; i < 2; i++) {
			if (reg.test(detailT)) {
				var mStr = RegExp.$1;
				detailT = detailT.replace(mStr, "");
				// setKindeDetail(detailT);
				// ueSetHtml('myj-editor',ueUnTransitionHtml(detailT));
				setEditorData('myj-editor', smtStrHand.unTransitionHtml(detailT));
			}
		}
	}
}

var setStrTestVal = function() {
	strTesting('', 'subjectTxtNum');
	strTesting('', 'subjectTxt');
	otherAttrNumTesting();
	// strTesting('','otherAttr');
	otherAttrTesting();
	otherAttrAgainTesting();
};

var setOtherAttrFy = function(fyLength, i, attrValue, otherAttrFyArr) {
	baiDuTranslate(attrValue, function(data) {
		if (data != "") {
			otherAttrFyArr.eq(i).val(data);
			if ((fyLength - 1) == i) {
				otherAttrNumTesting();
			}
			otherAttrTesting();
		}
	});

};

var reset = function() {
	$(".form-control").val("");
	$(".smsmInput").val("");
};

var syncProductModual = function() {
	var shopId = $("#shopId").val();
	if ($.trim(shopId) == "") {
		$.fn.message({
			type : "error",
			msg : "请选择速卖通店铺!"
		});
		return;
	}
	var moduleName = $("#moduleName").val();
	$.ajax({
		type : 'GET',
		url : 'smtShopInfoSync/syncProductModual.htm',
		data : {
			shopId : shopId,
			moduleName : moduleName
		},
		dataType : 'html',
		success : function(data) {
			$(".productModuleTable").html(data);
			if (data != null) {
				$.fn.message({
					type : "success",
					msg : "同步产品模板成功!"
				});
			} else {
				$.fn.message({
					type : "error",
					msg : "同步产品模板失败!"
				});
			}
		}
	});
};

var syncProductGroup = function() {
	// 设置店铺分组
	var groupIds = getGroupCheck();
	if ($.trim(groupIds) == "") {
		groupIds = "";
	}

	var shopId = $("#shopId").val();
	if ($.trim(shopId) == "") {
		$.fn.message({
			type : "error",
			msg : "请选择速卖通店铺!"
		});
		return;
	}
	$.ajax({
		type : 'GET',
		url : 'smtShopInfoSync/syncProductGroupNoAll.json',
		data : {
			shopId : shopId
		},
		dataType : 'json',
		success : function(data) {
			// 选择产品分组
			if (data != null) {
				var productGroupList = eval(data);
				setProductGroup(productGroupList, groupIds);
				$.fn.message({
					type : "success",
					msg : "同步产品分组成功!"
				});
			} else {
				$.fn.message({
					type : "error",
					msg : "同步产品分组失败!"
				});
			}
		}
	});
};
// add by fuyi 2015.4.29
var otherClickShowIpt = function(obj) {
	var str = '<input type="text" style="margin-left:10px;width:100px;" data-names="otherIpt" onkeyup="replaceProperty(this)" />';
	if ($(obj).closest('td').find('input[data-names="otherIpt"]').length == 0) {
		$(obj).closest('div').append(str);
	}
};
$(document).on('click', 'input[data-cid="4"]', function() {
	var specNum = $(this).attr('spec');

	if (specNum < 1 || specNum == undefined) {
		if (this.checked) {
			var obj = $(this).closest('label');
			otherClickShowIpt(obj);
		} else {
			$(this).closest('td').find('input[data-names="otherIpt"]').remove();
		}
	}
});
$(document).on('change', 'select', function() {
	var val = $(this).find('option:selected').attr('data-cid');
	if (val == 4) {
		otherClickShowIpt(this);
	} else {
		$(this).closest('td').find('input[data-names="otherIpt"]').remove();
	}
});
/*
 * sku价格最大值和最小值 add by fuyi 2015.5.5
 */
var priceMinAndMax = function() {
	var arr = [], maxPrice = "", minPrice = "", obj = {};
	$('#skuVariantList table').find('input[data-names="skuPrice"]').each(function() {
		arr.push($(this).val());
	});
	maxPrice = Math.max.apply(null, arr);
	minPrice = Math.min.apply(null, arr);
	obj = {
		productMinPrice : minPrice,
		productMaxPrice : maxPrice
	};
	return obj;
};

/*
 * add 发货地处理 by fuyi 2015.5.11
 */
$(document).on('click', 'a[data-name="fhd"]', function() {
	var type = $(this).attr('data-values');
	if (type == 'close') {
		$('#fhd').show();
		$(this).attr('data-values', 'open');
		$(this).html('- 收起');
	} else {
		$('#fhd').hide();
		$(this).attr('data-values', 'close');
		$(this).html('+ 展开');
	}
});

$(document).on('click', 'a[data-name="dcdp"]', function() {
	var type = $(this).attr('data-values');
	if (type == 'close') {
		$('#dcdp').show();
		$(this).attr('data-values', 'open');
		$(this).html('- 收起');
	} else {
		$('#dcdp').hide();
		$(this).attr('data-values', 'close');
		$(this).html('+ 展开');
	}
});

/** *************************引用产品分组 start*********************** */
var otheretProductGroup = function() {
	var shopId = $("#searchShop").val();
	// 生成分类树 （目标id,数组，配置，回选字符串‘选填’）
	var arr1 = [];
	// 测试
	// 配置
	var sittA = {
		check : 0,// checkbx 0不显示，1显示
		showNum : 0,// 统计数字 0不显示，1显示
		clickName : "",// clickName:'<a href="javascript:;">同步</a>'//分类后面显示的动做名
		showLevel : 1,// 初始展开级数
		objOption : "otherSelectProductList(this)"
	};
	// 选择产品分组
	var setOtherProductGroup = function(productGroupList, pushStr) {
		if (productGroupList != undefined) {
			productGroupList = eval(productGroupList);
			arr1 = productGroupList;
			$.fn.myj_tree.chooseTreeInit('treeB_c', arr1, sittA, pushStr);
		}
	};
	if (shopId != "") {
		// 取消分组选中
		// $("#treeB .chooseTree").html("");
		$.ajax({
			type : 'POST',
			async : false,
			url : 'smtShopInfoSync/list.json',
			data : {
				shopId : shopId
			},
			dataType : 'json',
			success : function(data) {
				var productGroupList = data.productGroupList;
				// 设置店铺分组
				// 选择产品分组
				setOtherProductGroup(productGroupList, "");
				$("#treeB_c").show();
				// 回填分组
				chooseGroupCheck();
			}
		});
	}
};

// 引用产品选择分组下拉列表点击事件
var otherSelectProductList = function(e) {
	var spanVal = $(e).closest('li').attr('groupName');
	var otherGroupId = $(e).closest('li').attr('groupId');
	$("#otherGroupSpan").html(spanVal);
	$("#otherfullCid").attr("data-id", otherGroupId);
	$("#treeB_c").hide();
};
function treeB_c_spanClick() {
	var treeB_c_spanVal = $("#treeB_c_span1").html();
	// console.log("==1"+treeB_c_spanVal);
	var treeB_c_spanId = $("#treeB_c_span1").attr("data-id");
	$("#otherGroupSpan").html(treeB_c_spanVal);
	$("#otherfullCid").attr("data-id", treeB_c_spanId);
	$("#treeB_c").hide();
}
$("#treeB_c_span1").hover(function() {
	$("#treeB_c_span1").css("color", "#428bca");
}, function() {
	$("#treeB_c_span1").css("color", "black");
});
$("#treeB_c_span2").hover(function() {
	$("#treeB_c_span2").css("color", "#428bca");
}, function() {
	$("#treeB_c_span2").css("color", "black");
});
function otherTreeB_c_spanClick() {
	var otherTreeB_c_spanVal = $("#treeB_c_span2").html();
	// console.log("==2"+otherTreeB_c_spanVal);
	var otherTreeB_c_spanId = $("#treeB_c_span2").attr("data-id");
	$("#otherGroupSpan").html(otherTreeB_c_spanVal);
	$("#otherfullCid").attr("data-id", otherTreeB_c_spanId);
	$("#treeB_c").hide();
}
$(document).bind('click', function(e) {
	var e = e || window.event; // 浏览器兼容性
	var elem = e.target || e.srcElement;
	while (elem) { // 循环判断至根节点，防止点击的是div子元素
		if (elem.id && elem.id == 'test') {
			return;
		}
		elem = elem.parentNode;
	}
	$('#treeB_c').css('display', 'none'); // 点击的不是div或其子元素
});
/** *************************产品分组 end*********************** */
// 引用相关
function used() {
	var url = "smtProduct/quotePageList.htm";
	var shopId = $("#shopId").val();
	$("#searchShop").val(shopId);
	$("#productStatusType option[value='']").prop("selected", true);
	$("#otherGroupSpan").html("选择分组");
	$("#otherfullCid").attr("data-id", "");
	quoteProduct(url, true);
	if ($("#searchShop").val() == "") {
		$("#otherfullCid").attr("disabled", true);
		$("#otherSelectDiv").css("cursor", "no-drop");
	} else {
		$("#otherfullCid").attr("disabled", false);
		$("#otherSelectDiv").css("cursor", "default");
	}
}

function quoteProduct(url, init) {
	$.ajax({
		type : "POST",
		url : url,
		data : {
			"pageNo" : 1,
			"shopId" : $('#searchShop').val(),
			"groupId" : $('#otherfullCid').attr("data-id"),
			"searchType" : $('#searchType').val(),
			"productStatusType" : $('#productStatusType').val(),
			"searchValue" : $('#searchValue').val(),
			"pageSize" : $('#pageSize').val(),
			"stateType" : $('#stateType').val(),
			"sortTypeQuote" : $('#sortTypeQuote').val(),
			"sortValueQuote" : $('#sortValueQuote').val()
		},
		dataType : "html",
		success : function(data) {
			$('#pageList').html(data);
			if (init) {// 初始化加载
				$("#quoteModal").modal("show");
			}
			quoteInitPage(url);
		}
	});
}

function quoteSelectShop() {
	var url = "smtProduct/quotePageList.htm";
	if ($("#searchShop").val() == "") {
		$("#otherGroupSpan").html("选择分组");
		$("#otherfullCid").attr("data-id", "");
		$("#otherfullCid").attr("disabled", true);
		$("#otherSelectDiv").css("cursor", "no-drop");
	} else {
		$("#otherGroupSpan").html("选择分组");
		$("#otherfullCid").attr("data-id", "");
		$("#otherfullCid").attr("disabled", false);
		$("#otherSelectDiv").css("cursor", "default");
	}
	quoteProduct(url, false);
}

// 根据条件搜索
function btnSearchIt() {
	var url = "smtProduct/quotePageList.htm";
	var searchValue = $.trim($('#searchValue').val());
	$.ajax({
		type : "POST",
		url : url,
		data : {
			"shopId" : $('#searchShop').val(),
			"groupId" : $('#otherfullCid').attr("data-id"),
			"searchType" : $('#searchType').val(),
			"productStatusType" : $('#productStatusType').val(),
			"searchValue" : searchValue,
			"pageSize" : $('#pageSize').val(),
			"stateType" : $('#stateType').val(),
			"sortTypeQuote" : $('#sortTypeQuote').val(),
			"sortValueQuote" : $('#sortValueQuote').val()
		},
		dataType : "html",
		success : function(data) {

			$('#pageList').html(data);
			quoteInitPage(url);
			document.getElementById('pageList').scrollTop = 0;
		}
	});
}

function quoteInitPage(url) {
	var pageSizez = $('#pageSize').val();
	var totalSize = $('#totalSize').val();
	if (parseInt(totalSize, 10) > 0) {
		options.totalPages = $('#totalPage').val();
		options.currentPage = $('#pageNo').val();
		options.numberOfPages = pageSizez;
		options.numberOfPagesArr = [ 5, 30, 50, 100 ];
		options.totalSize = $('#totalSize').val();
		options.goOffPage = true;
		options.onPageClicked = function(event, originalEvent, type, page) {
			// $('#loading').modal('show');
			$.ajax({
				type : "POST",
				url : url,
				data : {
					"pageNo" : page,
					"pageSize" : pageSizez,
					"shopId" : $('#searchShop').val(),
					"groupId" : $('#otherfullCid').attr("data-id"),
					"searchType" : $('#searchType').val(),
					"productStatusType" : $('#productStatusType').val(),
					"searchValue" : $('#searchValue').val(),
					"stateType" : $('#stateType').val(),
					"sortTypeQuote" : $('#sortTypeQuote').val(),
					"sortValueQuote" : $('#sortValueQuote').val()
				},
				dataType : "html",
				success : function(data) {
					$('#pageList').html(data);
					document.getElementById('pageList').scrollTop = 0;
					quoteInitPage(url);
				}
			});
		};

		options.onPageSelected = function(event) {
			// $('#loading').modal('show');
			var pageSelect = $(event.target);
			$.ajax({
				type : "POST",
				url : url,
				data : {
					"pageNo" : 1,
					"pageSize" : pageSelect.val(),
					"shopId" : $('#searchShop').val(),
					"groupId" : $('#otherfullCid').attr("data-id"),
					"searchType" : $('#searchType').val(),
					"productStatusType" : $('#productStatusType').val(),
					"searchValue" : $('#searchValue').val(),
					"stateType" : $('#stateType').val(),
					"sortTypeQuote" : $('#sortTypeQuote').val(),
					"sortValueQuote" : $('#sortValueQuote').val()
				},
				dataType : "html",
				success : function(data) {
					$('#pageList').html(data);
					document.getElementById('pageList').scrollTop = 0;
					quoteInitPage(url);
				}
			});
		};

		options.onPageJump = function(event) {
			$('#loading').modal('show');
			var pageJump = $(event.target);
			$.ajax({
				type : "POST",
				url : url,
				data : {
					"pageNo" : pageJump.prevAll("input[zdyPageInput='zdy']").val(),
					"pageSize" : $("select[name='pageselct']").val(),
					"shopId" : $('#searchShop').val(),
					"groupId" : $('#otherfullCid').attr("data-id"),
					"searchType" : $('#searchType').val(),
					"productStatusType" : $('#productStatusType').val(),
					"searchValue" : $('#searchValue').val(),
					"stateType" : $('#stateType').val(),
					"sortTypeQuote" : $('#sortTypeQuote').val(),
					"sortValueQuote" : $('#sortValueQuote').val()
				},
				dataType : "html",
				success : function(data) {
					$('#pageList').html(data);
					document.getElementById('pageList').scrollTop = 0;
					quoteInitPage(url);
					$('#loading').modal('hide');
				}
			});
		};
		$('#downPage').bootstrapPaginator(options);
		// $('#upPage').bootstrapPaginator(options);
	} else {
		$('#downPage').empty();
	}
}

// 引用产品加入收藏
function collectProduct(productId, iscollection) {
	$.ajax({
		type : "POST",
		url : "smtProduct/collectProduct.json",
		data : {
			"productId" : productId,
			"isCollect" : iscollection
		},
		dataType : "json",
		success : function(data) {
			if (1 == data) {
				if (iscollection == 1) {
					$.fn.message({
						type : "success",
						msg : "取消收藏成功！"
					});
				} else {
					$.fn.message({
						type : "success",
						msg : "加入收藏成功！"
					});
				}
				btnSearchIt();
			} else {
				$.fn.message({
					type : "error",
					msg : "加入收藏失败！"
				});
			}
		}
	});
}

// 更新引用次数
function keepCount(productId, quoteCount) {
	$.ajax({
		type : "POST",
		url : "smtProduct/remberQuoteCount.json",
		data : {
			"productId" : productId,
			"quoteCount" : quoteCount
		},
		dataType : "json",
		success : function(data) {

		}
	});
}

function qianhuanLi(val) {
	$('#stateType').val(0 == val ? 0 : 1);
	/*
	 * if(0 == val){ $('#stateType').val(0); }else if(1 == val){
	 * $('#stateType').val(1); }
	 */
	btnSearchIt();
}

function caretSort(type, value) {
	$("#sortTypeQuote").val(type);
	if (type == 1) {
		$("#sortValueQuote").val(value == 'desc' ? '' : 'desc');
		/*
		 * if(value == 'desc'){ $("#sortValueQuote").val(''); }else {
		 * $("#sortValueQuote").val("desc"); }
		 */
	}
	btnSearchIt();
}

function caretSortTime(type, value) {
	$("#sortTypeQuote").val(type);
	$("#sortValueQuote").val(value == 'desc' ? '' : 'desc');
	/*
	 * if(value == 'desc'){ $("#sortValueQuote").val(''); }else {
	 * $("#sortValueQuote").val('desc'); }
	 */
	btnSearchIt();
}

//
$(document).on('change', 'select[cid="attrSelect"]', function() {
	var moreattribute = $(this).attr('moreattribute'), cId = $(this).find('option:selected').attr('data-cid'), pId = $(this).closest('tr').find('[data-names="attrNames"]').attr('id'), length = $('#productAttribute table').find('tr[data-names="newTr"]').length;
	if (moreattribute == 1) {
		var arr = childAttributeList(pId, cId), str = newAttrList(arr);
		for (var i = 0; i < length; i++) {
			var names = $(this).closest('tr').next().attr('data-names');
			if (names == 'newTr') {
				$(this).closest('tr').next().remove();
			}
		}
		if (str != '' && str != undefined) {
			var $Str = $(str);
			$(this).closest('tr').after($Str);
			$Str.find('.chosen-select').chosen({
				search_contains : true
			});// 注册插件
		}
	}
});
function newAttrList(arr) {
	var str = '';
	for (var i = 0; i < arr.length; i++) {
		var sku = arr[i].sku, showType = arr[i].attributeShowTypeValue, names = arr[i].nameZh, namesEn = arr[i].nameEn, required = arr[i].required, keyAttribute = arr[i].keyAttribute, namesId = arr[i].arrtNameId, spec = arr[i].spec, visible = arr[i].viseble, values = arr[i].values, customizedName = arr[i].customizedName, customizedPic = arr[i].customizedPic, units = arr[i].units, inputType = arr[i].inputType, moreAttribute = arr[i].moreAttribute;
		if (!moreAttribute) {
			moreAttribute = 0;
		}
		// 调用非sku属性展示方法
		str += productAttributeInitLine(names, namesId, required, keyAttribute, showType, values, units, inputType, moreAttribute);
	}
	return str;
}

$('[data-toggle="tooltip"]').tooltip();
$('.productTitTextSize').click(function() {
	var str = $('.productTitle').val();
	var newStr = str.replace(/\s[a-z]/g, function($1) {
		return $1.toLocaleUpperCase()
	}).replace(/^[a-z]/, function($1) {
		return $1.toLocaleUpperCase()
	}).replace(/\sOr[^a-zA-Z]|\sAnd[^a-zA-Z]|\sOf[^a-zA-Z]|\sAbout[^a-zA-Z]|\sFor[^a-zA-Z]|\sWith[^a-zA-Z]|\sOn[^a-zA-Z]/g, function($1) {
		return $1.toLowerCase()
	});
	$('.productTitle').val(newStr);
});

function batchChoicePic(editorPic) {
	$("#batchChoicePicFrame").attr("src", 'album/selImgIframe.htm');
	// $("#batchChoicePicSpace").find('button[onclick="showBatchChoicePicSpace(this);"]').attr("editorId",id);
	editorInfo = editorPic;
	$("#batchChoicePicSpace").modal("show");
}

// 图片银行图片处理，从子窗口中得到选中的图片地址
function showBatchChoicePicSpace() {
	var imgHtml = document.getElementById('batchChoicePicFrame').contentWindow.getSelectImg();
	if (editorInfo) {
		insertEditorData(editorInfo.editorId, imgHtml);
		editorInfo = null;
	}
	$('#batchChoicePicSpace').modal('hide');
}

/** ************************引用模板相关 begin***************** */
var showProductModule = function() {
	var shopId = $('#shopId').val();
	if (!shopId) {
		$.fn.message({
			type : "error",
			msg : "请先选择店铺！"
		});
		return;
	}
	$.ajax({
		type : "POST",
		url : "userTemplate/quotePageList.htm",
		data : {
			"pageNo" : 1,
			"pageSize" : $('#productTemplatePageSize').val(),
			"shopId" : shopId,
			"platform" : 'smt',
			"searchType" : $('#productModuleSearchType').val(),
			"searchValue" : $('#productModuleSearchValue').val()
		},
		dataType : "html",
		success : function(data) {
			$('#productModulePageList').html(data);
			$("#productModuleQuoteModal").modal("show");
			$('#productModuleQuoteModal form input[type="text"]').focus();
		}
	});
};
/** ************************引用模板相关 end********************** */

/** ************************尺码模板相关 begin***************** */
var showSizeTemplateModule = function(showClass, hideClass) {
	$("." + showClass).addClass("myj-hide");
	$("." + hideClass).addClass("myj-hide");
	var shopId = $('#shopId').val();
	$.ajax({
		type : "POST",
		url : "userSizeTemplate/quotePageList.htm",
		data : {
			"pageNo" : 1,
			"pageSize" : $('#sizeTemplatePageSize').val(),
			"shopId" : shopId,
			"platform" : 'smt',
			"searchType" : $('#sizeTemplateModuleSearchType').val(),
			"searchValue" : $('#sizeTemplateModuleSearchValue').val()
		},
		dataType : "html",
		success : function(data) {
			$('#sizeTemplateModulePageList').html(data);
			$('#sizeTemplateModuleQuoteModal form input[type="text"]').focus();
		}
	});
};

var showSizeTemplateToEditer = function(data) {
	if (data.html && editorInfo) {
		insertEditorData(editorInfo.editorId, data.html);
		editorInfo = null;
	}
	// data.html && editor.insertHtml(data.html);
	$("#categoryModules").modal("hide");
};
/** ************************尺码模板相关 end********************** */

// 自定义属性检测
$(document).on('focusout', '#otherAttr input', function() {
	var obj = $(this);
	strTesting(obj, 'otherAttr');
	otherAttrAgainTesting();
});

/**
 * 保存产品历史品牌
 * 
 * @param shopId
 */
var saveProductBrand = function(shopId) {
	var brandSelect = $('#productAttribute').find('select[attrid="2"] option:selected');
	if (brandSelect) {
		var brandId = $(brandSelect).attr('data-cid');
		var brandName = $(brandSelect).text();
		if (shopId && brandId && brandName) {
			$.ajax({
				type : 'POST',
				url : "smtProduct/addProductBrandHistory.json",
				data : {
					shopId : shopId,
					brandId : $.trim(brandId) + "",
					brandName : brandName
				},
				dataType : 'json',
				timeout : 60000,
				success : function(data) {

				},
				error : function() {
					$.fn.message({
						type : "error",
						msg : "新增历史品牌失败！"
					});
				}
			});
		}
	}
};

/**
 * 删除历史品牌
 * 
 * @param id
 */
var deleteProductBrand = function(id) {
	if (id) {
		$.ajax({
			type : 'POST',
			url : "<%=basePath%>/smtProduct/deleteProductBrand.json",
			data : {
				id : id
			},
			dataType : 'json',
			timeout : 60000,
			success : function(data) {
				if (data == 0) {
					$.fn.message({
						type : "error",
						msg : "删除历史品牌失败"
					});
				}
			},
			error : function() {
				$.fn.message({
					type : "error",
					msg : "删除历史品牌失败！"
				});
			}
		});
	}
};

var toDisabled = function(dxmState, activity) {
	if (dxmState == 'online' && 'true' == activity) {
		$('.onlineProductInfo input').attr('disabled', 'disabled');
		$('.onlineProductInfo button').attr('disabled', 'disabled');
		$('.onlineProductInfo .imgDivDown a').hide();
		$('.onlineProductInfo .smtAMakeRemoveBtnLocation').hide();
		$('.onlineProductInfo [data-names="otherAttrRemove"]').hide();
		$('.onlineProductInfo select').prop('disabled', 'disabled');
		$('#subject').removeAttr('disabled');
		$('#fullCid').removeAttr('disabled');
		$('input[name="wsValidNum"]').removeAttr('disabled');
	}
};
var resizecall = function(url, obj) {
	var $img = $('.resizeOut').find('img[src="' + url + '"]');
	if (+$img.length) {
		$img.closest('li').find('.imgSize').html(obj.w + ' X ' + obj.h);
	}
};
// 不同国际不同运费模板
var shipToInternational = {
	shipToData : [ {
		id : "RU",
		name : "Russian Federation"
	}, {
		id : "US",
		name : "United States"
	}, {
		id : "CA",
		name : "Canada"
	}, {
		id : "ES",
		name : "Spain"
	}, {
		id : "FR",
		name : "France"
	}, {
		id : "UK",
		name : "United Kingdom"
	}, {
		id : "NL",
		name : "Netherlands"
	}, {
		id : "IL",
		name : "Israel"
	}, {
		id : "BR",
		name : "Brazil"
	}, {
		id : "CL",
		name : "Chile"
	}, {
		id : "AU",
		name : "Australia"
	} ],
	shipToTemplateTable : '<td class="adjust-price"><span></span>区域调价：' + '<span data-names="attrNames" data-requited="" data-type="checkbox"></span></td>' + '<td colspan="3"><div class="m-top5 m-bottom5">' + '<a  href="javascript:" data-name="dcdp" data-values="close">+ 展开</a></div>' + '<div style="display:none" id="dcdp">' + '<div class="m-bottom5"><span class="gray-c">商品零售价作为基准价，开放部分"Ship to"区域，可以在基准价基础上进行调整。</span></div>' + '<table class="myj-table table-aeop" id="aeopNationalQuoteConfigurationTB">' + '<thead>' + '<tr>' + '<th style="display: table-cell;">运送区域</th>' + '<th style="display: table-cell;">调价方式:' + '<select class="form-component w80 m-left10" id="priceHolder" onchange="changeMode(this);">' + '<option value="percentage" selected="selected">按比例</option>' + '<option id="" value="relative"">按金额</option></select>' + '</th>' + '<th style="display: table-cell;">商品零售价</th>' + '<th style="display: table-cell;">调整后价格</th>' + '</tr>' + '</thead>' + '<tbody class="smtPrice"></tbody></table></div></td>',
	shipToTemplateTableTr : '<tr>' + '<td><span id="" name="nation"></span></td>' + '<td>' + '<select class="form-component modify-price-sel m-right5" name="direction" onchange="changeDerection(this);">' + '<option name="minus" value="-1">-</option>' + '<option name="plus" value="1" selected="selected">+</option>' + '</select>' + '<span name="relative"></span>' + '<input class="modify-price-ipt formtype="shippingNationPrice" m-left5 m-right5 modifyPrice" type="text" data-names="value" value="0" ' + 'onblur="changePrice(this);" onkeyup="clearMistakeNumber(this);" />' + '<span name="percentageSimple">%</span>' + '<a href="javascript:" class="smtPrice_a" data-toggle="tooltip" data-placement="top" title="" ' + 'data-original-title="应用到其他国家" onclick="setAllCountry(this);">' + '<span class="smtPrice_aIcon glyphicon glyphicon-send"  style="display: inline;"></span></a>' + '<div><span class="f-red" name="msg"></span></div></td>' + '<td>$<span name="priceRange"></span></td>' + '<td>$<span name="adjustedPriceRanged"></span></td>' + '</tr>' + '<tr>'
};
$(function() {
	var skuArr = $("#aeopAeProductSKUs").val(), shipToTempleTable = $(shipToInternational.shipToTemplateTable), shipToData = shipToInternational.shipToData;
	$.each(shipToData, function(si, sj) {
		var shipToTr = $(shipToInternational.shipToTemplateTableTr);
		shipToTr.find('[name="nation"]').attr('id', sj.id).html(sj.name);
		shipToTempleTable.find('tbody').append(shipToTr);
	});
	// console.log("skuArr"+skuArr);
	$('.setUpNationalFre').append(shipToTempleTable).removeClass('myj-hide');

	// 初始化零售价和调整后的价格
	initPriceInfo();

	// 初始化分国家设置内容
	initaeopNationalQuoteConfiguration();
	$('input[data-names="value"]').off('focus');
	$('input[data-names="value"]').on('focus', function() {
		$(this).closest('tbody').find('.smtPrice_a').css('visibility', 'hidden');
		$(this).closest('tr').find('.smtPrice_a').css('visibility', 'visible');
	});
});

function initPriceInfo() {
	// 设置零售价范围
	var max = 0;
	var min;
	$("input[data-names='skuPrice']").each(function() {
		var num = $(this).val() * 1;
		if (!min) {
			min = num;
		}
		if (num > max) {
			max = num;
		}
		if (num < min) {
			min = num;
		}
	});

	// 取单品SKU价格
	if (!min) {
		var price = $("#skuPrice").val();
		if (price) {
			min = price;
			max = price
		} else {
			min = 0;
		}
	}
	if (max == min) {
		$("span[name='priceRange']").text(min);
	} else {
		$("span[name='priceRange']").text(min + "-" + max);
	}
	var nmin = 0;
	var nmin = Number(min);

	// 调整后的价格范围
	$("#aeopNationalQuoteConfigurationTB input[data-names='value']").each(function() {
		var type = $("#priceHolder").val();
		var inputValue = $(this).val();
		var selectValue = $(this).closest('td').find("select[name='direction']").val();
		var adjustedPriceRange;
		switch (type) {
		case "percentage":
			var rmax = max * (1 + selectValue * (inputValue / 100));
			var rmin = nmin * (1 + selectValue * (inputValue / 100));
			if (Number(rmax) == Number(rmin)) {
				adjustedPriceRange = rmin.toFixed(2);
			} else {
				adjustedPriceRange = rmin.toFixed(2) + "-" + rmax.toFixed(2);
			}
			break;
		case "relative":
			var rmax = Number(max) + selectValue * inputValue;
			var rmin = Number(nmin) + selectValue * inputValue;
			if (Number(rmax) == Number(rmin)) {
				adjustedPriceRange = rmin.toFixed(2);
			} else {
				adjustedPriceRange = rmin.toFixed(2) + "-" + rmax.toFixed(2);
			}
			break;
		}
		$(this).closest('tr').find("span[name='adjustedPriceRanged']").text(adjustedPriceRange);
	});
}
function initPriceInfo1() { // 批量设置零售价
	var price = $("#batchSkuPrice").val();
	$("span[name='priceRange']").text(price);
	// 调整后的价格范围
	$("#aeopNationalQuoteConfigurationTB input[data-names='value']").each(function() {
		var type = $("#priceHolder").val();
		var inputValue = $(this).val();
		var selectValue = $(this).closest('td').find("select[name='direction']").val();
		var adjustedPriceRange;
		switch (type) {
		case "percentage":
			var per = price * (1 + selectValue * (inputValue / 100));
			adjustedPriceRange = per.toFixed(2);
			break;
		case "relative":
			var rel = Number(price) + selectValue * inputValue;
			adjustedPriceRange = rel.toFixed(2);
			break;
		}
		$(this).closest('tr').find("span[name='adjustedPriceRanged']").text(adjustedPriceRange);
	});
}

function initaeopNationalQuoteConfiguration() {
	var obj = $("#aeopNationalQuoteConfiguration").val();
	// console.log(obj);
	if (obj) {
		obj = JSON.parse(obj);
		if (obj) {
			var type = obj.configurationType;
			if (type) {
				// 设置调价默认值
				$("#priceHolder").val(type);
				changeMode($("#priceHolder"));
			}
			var data = obj.configurationData;
			if (data) {
				data = JSON.parse(data);
				for (var i = 0; i < data.length; i++) {
					var country = data[i].shiptoCountry;
					var percentage;
					switch (type) {
					case "percentage":
						percentage = data[i].percentage;
						break;
					case "relative":
						percentage = data[i].relative;
						break;
					}
					// country="RU";
					var choose = "#" + country;
					// 填充符号
					if (Number(percentage) < 0) {
						$(choose).parent('td').parent('tr').find('select[name="direction"]').val(-1);
						$(choose).parent('td').parent('tr').find('input[data-names="value"]').val(percentage.toString().replace("-", ""));
					} else {
						$(choose).parent('td').parent('tr').find('select[name="direction"]').val(-1);
						$(choose).parent('td').parent('tr').find('input[data-names="value"]').val(percentage.toString().replace("-", ""));
					}
				}
			}
			var input = $("#aeopNationalQuoteConfigurationTB input[data-names='value']");
			input.each(function() {
				changePrice(this);
			});

		} else {
			// 如果不存在该属性
			var input = $("#aeopNationalQuoteConfigurationTB input[data-names='value']");
			input.each(function() {
				changePrice(this);
			});
		}
	}
}

function changeMode(obj) {
	clearStyles();
	// 变换绑定事件 按比例界面语序输入整数，按金额界面允许输入两位小数
	var modeholder = $("#priceHolder").val();
	if ('percentage' == modeholder) {
		$('#aeopNationalQuoteConfigurationTB [data-names="value"]').attr("onkeyup", "clearMistakeNumber(this);");
	} else {
		$('#aeopNationalQuoteConfigurationTB [data-names="value"]').attr("onkeyup", "clearNoNum(this)");
	}
	var aeop = $("#aeopNationalQuoteConfiguration").val();
	// console.log("aeop"+aeop);
	var isDraft = false;
	if ("" == aeop || aeop.length == 2) {
		isDraft = true;
	}
	// 本地产品 清空
	if (aeop.length == 2) {
		$('#aeopNationalQuoteConfigurationTB input[data-names="value"]').val(0);
		initPriceInfo();
	}
	if ("" == aeop) {
		aeop = [];
	}
	var aobj = eval("(" + aeop + ")");
	if (aobj && !isDraft) {
		var aeop = eval("(" + aeop + ")");
		var type = aeop.configurationType;
		var obj = $(obj);
		$("input[data-names='value']").val(0);
		if (obj.val() == 'percentage') {
			$("span[name='relative']").text("");
			$("span[name='percentageSimple']").text("%");
		}
		if (obj.val() == 'relative') {
			$("span[name='percentageSimple']").text("");
			$("span[name='relative']").text("$");
		}
		if (obj.val() == type) {
			var data = aeop.configurationData;
			for (var i = 0; i < data.length; i++) {
				var country = data[i].shiptoCountry;
				var percentage;
				switch (type) {
				case "percentage":
					percentage = data[i].percentage;
					break;
				case "relative":
					percentage = data[i].relative;
					break;
				}
				var choose = "#" + country;
				// 填充符号
				if (Number(percentage) < 0) {
					$(choose).parent().parent().find("td select").val(-1);
					$(choose).parent().parent().find('input[data-names="value"]').val(percentage.toString().replace("-", ""));
				} else {
					$(choose).parent().parent().find("td select").val(1);
					$(choose).parent().parent().find('input[data-names="value"]').val(percentage);
				}
				var aeop = $(choose).parent().parent().find("input");
				changePrice(aeop);
			}
		} else {
			var max = 0;
			var min;
			$("input[data-names='skuPrice']").each(function() {
				var num = $(this).val() * 1;
				if (!min) {
					min = num;
				}
				if (num > max) {
					max = num;
				}
				if (num < min) {
					min = num;
				}
			});

			// 取单品SKU价格
			if (!min) {
				var price = $("#skuPrice").val();
				if (price) {
					min = price;
					max = price
				} else {
					min = 0;
				}
			}

			if (max == min) {
				$("span[name='adjustedPriceRanged']").text(min).closest('td').css('color', '#434649');
				$("#aeopNationalQuoteConfigurationTB input[data-names='value']").css('border-color', '#ccc');
				$("#aeopNationalQuoteConfigurationTB span[name='msg']").text("");
			} else {
				$("span[name='adjustedPriceRanged']").text(min + "-" + max).closest('td').css('color', '#434649');
			}
		}
	} else {
		// 本地未上传产品
		// 取零售价价格范围
		var max = 0;
		var min;
		$("input[data-names='skuPrice']").each(function() {
			var num = $(this).val() * 1;
			if (!min) {
				min = num;
			}
			if (num > max) {
				max = num;
			}
			if (num < min) {
				min = num;
			}
		});

		// 取单品SKU价格
		if (!min) {
			var price = $("#skuPrice").val();
			if (price) {
				min = price;
				max = price
			} else {
				min = 0;
			}
		}

		$(obj).removeAttr("style");
		$(obj).parent().find("span[name='msg']").text("");
		$(obj).parent().parent().parent().parent().find("tbody tr").removeAttr("style");
		// 更改符号
		if ($(obj).val() == 'percentage') {
			$("span[name='relative']").text("");
			$("span[name='percentageSimple']").text("%");
		}
		if ($(obj).val() == 'relative') {
			$("span[name='percentageSimple']").text("");
			$("span[name='relative']").text("$");
		}

		if (max == min) {
			$("span[name='priceRange']").text(min);
			$("span[name='adjustedPriceRanged']").text(min);
		} else {
			$("span[name='priceRange']").text(min + "-" + max);
			$("span[name='adjustedPriceRanged']").text(min + "-" + max);
		}

		var aeop = $(choose).parent().parent().find("input");
		$("aeopNationalQuoteConfigurationTB input[data-names='value']").each(function() {
			changePrice(this);
		});
	}
}

// 更换符号
function changeDerection(direction) {
	var obj = $(direction).parent().find("input[data-names='value']");
	changePrice(obj);
}

// 更改价格
function changePrice(obj) {

	var $this = $(obj);
	var value = $this.val();
	var mode = $("#priceHolder").val();
	var select = $this.parent().find("select").val();
	var lmin;
	// 获取价格最大值和最小值
	var max = 0;
	var min;

	$("input[data-names='skuPrice']").each(function() {
		var num = $(this).val() * 1;
		if (!min) {
			min = num;
		}
		if (num > max) {
			max = num;
		}
		if (num < min) {
			min = num;
		}
	});

	if (!min) {
		var price = $("#skuPrice").val();
		if (price) {
			min = price;
			max = price;
		} else {
			min = 0;
		}
	}
	lmin = min;
	if (mode == 'percentage') {
		// 比例调价
		if (max == min) {
			var adjustPrice = min * (1 + select * value / 100);
			$(obj).parent().parent().find("td span[name='adjustedPriceRanged']").text(adjustPrice.toFixed(2));
		} else {
			var rmax = max * (1 + select * value / 100);
			var rmin = min * (1 + select * value / 100);
			var adjustPrice = rmin.toFixed(2) + "-" + rmax.toFixed(2);
			$(obj).parent().parent().find("td span[name='adjustedPriceRanged']").text(adjustPrice);
		}
	} else {
		// 固价调价
		if (max == min) {
			var adjustPrice = Number(min) + (select * value);
			$(obj).parent().parent().find("td span[name='adjustedPriceRanged']").text(adjustPrice.toFixed(2));
		} else {
			var rmax = max + (select * value);
			var rmin = min + (select * value);
			var adjustPrice = rmin.toFixed(2) + "-" + rmax.toFixed(2);
			$(obj).parent().parent().find("td span[name='adjustedPriceRanged']").text(adjustPrice);
		}
	}

	// 判断-30和100范围
	// 验证红色
	$(obj).attr({
		style : "border-color: #ccc"
	});
	$(obj).parent().find("span[name='msg']").text("");

	if (mode == "percentage") {
		if (Number(select) < 0 && value > 30) {
			$(obj).attr({
				style : "border-color: #ec4339"
			});
			$(obj).parent().find("span[name='msg']").text("下调范围不能超过30%");
		}
		if (Number(select) > 0 && value > 100) {
			$(obj).attr({
				style : "border-color: #ec4339"
			});
			$(obj).parent().find("span[name='msg']").text("不能高于基准价的100%比例");
		}
	} else {
		if (Number(select) < 0 && Number(value) > Number(lmin) * 0.3) {
			$(obj).attr({
				style : "border-color: #ec4339"
			});
			$(obj).parent().find("span[name='msg']").text("下调范围不能超过30%");
		}
		if (Number(select) > 0 && Number(value) > Number(lmin)) {
			$(obj).attr({
				style : "border-color: #ec4339"
			});
			$(obj).parent().find("span[name='msg']").text("不能高于基准价的100%");
		}
	}

	// 判断颜色
	$(obj).closest('tr').find("td:last").css({
		'color' : "#434649"
	});
	if (Number(select) > 0 && Number(value) > 0) {
		$(obj).closest('tr').find("td:last").css({
			"color" : "#ec4339"
		});
	}
	if (Number(select) < 0 && Number(value) > 0) {
		$(obj).closest('tr').find("td:last").css({
			"color" : "#7cb82f"
		});
	}
	// 非空判断和小于0
	if (value == '' || value < 0) {
		var value = $(obj).val(0);
	}

	// 判断颜色
	chectkColor();
}

// 获取国家信息设置
// 格式为 {"configurationType":"relative",
// "configurationData":[{"relative":1,"shiptoCountry":"RU"},{"relative":2,"shiptoCountry":"US"},{"relative":-1,"shiptoCountry":"CA"}]}
var getNationalPriceData = function() {
	var aeopNationalQuoteConfiguration = $("#aeopNationalQuoteConfiguration");
	var mode = $("#priceHolder").val();
	var info = [];
	$("#aeopNationalQuoteConfigurationTB tbody tr").each(function() {
		var shiptoCountry = $(this).find("span[name='nation']").eq(0).attr("id");
		var selectValue = $(this).find("select[name='direction']").val();
		var inputValue = $(this).find("input[data-names='value']").val();
		var value = Number(selectValue) * Number(inputValue);
		// console.log(selectValue+""+inputValue);
		if (shiptoCountry && selectValue && inputValue && value) {
			// console.log("国家"+shiptoCountry+"正负"+selectValue+"值"+inputValue+"最终值"+value);
			// 范围做验证
			if (mode == 'percentage') {
				if (value > 100 || value < -30) {
					$.fn.message({
						"type" : "error",
						"msg" : "分国家设置价格超范围"
					});
					return;
				}
			} else {
				// 取最小价格
				var max = 0;
				var min;
				$("input[data-names='skuPrice']").each(function() {
					var num = $(this).val() * 1;
					if (!min) {
						min = num;
					}
					if (num > max) {
						max = num;
					}
					if (num < min) {
						min = num;
					}
				});
				if (!min) {
					min = $("#skuPrice").val();
				}
				var rmax = min * 1;
				var rmin = min * 0.3 * -1;
				if (value > rmax || value < rmin) {
					$.fn.message({
						"type" : "error",
						"msg" : "分国家设置价格超范围"
					});
					return;
				}
			}
			var dataKey = shiptoCountry;
			var dataValue = value;
			var data = {};
			data[mode] = dataValue;
			data['shiptoCountry'] = dataKey;
			info.push(data);
		}
	});

	if (info.length == 0) {
		return "{}";
	}
	var nationPriceData = {
		"configurationType" : mode,
		"configurationData" : JSON.stringify(info)
	};

	return JSON.stringify(nationPriceData);
};

// 为所有的价格iuput框绑定blur事件
$(document).on('blur', "#skuVariantList input[data-names='skuPrice']", function() {
	initPriceInfo();
});

$(document).on('blur', "#skuPrice", function() {
	initPriceInfo();
});

// 判断增长颜色颜色
function chectkColor() {
	$('#aeopNationalQuoteConfigurationTB tr input[data-names="value"]').each(function() {
		var value = $(this).val();
		var select = $(this).parent().find('select[name="direction"]').val();
		if (Number(select) > 0 && Number(value) > 0) {
			$(this).closest('tr').find("td:last").attr({
				"style" : "color:red"
			});
		}
		if (Number(select) < 0 && Number(value) > 0) {
			$(this).closest('tr').find("td:last").attr({
				"style" : "color:green"
			});
		}
	});
}

function clearStyles() {
	$('#aeopNationalQuoteConfigurationTB tr input[data-names="value"]').each(function() {
		$(this).removeAttr("style");
		$(this).closest("span[name='msg']").text("");
		$(this).closest('tr').find("td:last").removeAttr("style");
		$(this).closest('td').find('span[name="msg"]').text('');
	});
}

// 设置到应用其他国家
$(function() {
	$("[data-toggle='tooltip']").tooltip();
});

function setAllCountry(obj) {

	$(obj).closest('tr').find('input.modifyPrice').focus();

	var value = $(obj).closest('td').find("input[data-names='value']").val();
	var selectValue = $(obj).closest('td').find("select[name='direction']").val();
	// 设置值
	$(obj).closest('tbody').find("input[data-names='value']").each(function() {
		$(this).val(value);
	});
	// 设置方向
	$(obj).closest('tbody').find('select[name="direction"]').each(function() {
		$(this).val(selectValue);
	});
	initPriceInfo();
	chectkColor();
}
